Android Kotlin解析Json文件(Gson)

MainActivity.kt

package com.example.fredric.sendrequestwithokhttp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.xml.sax.InputSource
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import javax.xml.parsers.SAXParserFactory

inline fun  KTypeToken() = object : TypeToken() {} .type

class MainActivity : AppCompatActivity(), View.OnClickListener{


    var responseText: TextView? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var sendRequest = findViewById

ContentHandler.kt

package com.example.fredric.sendrequestwithokhttp

import android.util.Log
import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler

class ContentHandler : DefaultHandler() {

    var nodeName: String? = null
    var id: StringBuilder? = null
    var name: StringBuilder? = null
    var version: StringBuilder? = null


    @Throws(SAXException::class)
    override fun startDocument() {
        id = StringBuilder()
        name = StringBuilder()
        version = StringBuilder()
    }


    @Throws(SAXException::class)
    override fun endDocument() {
        super.endDocument()
    }


    @Throws(SAXException::class)
    override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
        nodeName = localName
    }


    @Throws(SAXException::class)
    override fun characters(ch: CharArray, start: Int, length: Int) {
        if("id".equals(nodeName)) {
            id?.append(ch,start,length)
        }else if("name".equals(nodeName)) {
            name?.append(ch,start,length)
        }else if("version".equals(nodeName)) {
            version?.append(ch, start, length)
        }
    }

    @Throws(SAXException::class)
    override fun endElement(uri: String, localName: String, qName: String) {
        if("app".equals(localName)) {
            Log.d("ContentHandler","id is :" + id?.toString()?.trim())
            Log.d("ContentHandler","name is :" + name?.toString()?.trim())
            Log.d("ContentHandler","version is :" + version?.toString()?.trim())

            id?.setLength(0)
            name?.setLength(0)
            version?.setLength(0)
        }
    }

}

App.kt

package com.example.fredric.sendrequestwithokhttp

data class App(
        var id: String?,
        var name: String?,
        var version: String?
)

程序运行效果,


Screen Shot 2018-07-24 at 6.38.15 AM.png

你可能感兴趣的:(Android Kotlin解析Json文件(Gson))