kotlin 读取json文件_如何在Kotlin中解析JSON?

89243975287427ed800e960c1d0d40a9.png

慕用2447696

没有外部库(在Android上)要解析此:val jsonString = """    {       "type":"Foo",       "data":[          {             "id":1,             "title":"Hello"          },          {             "id":2,             "title":"World"          }       ]    }        """使用这些类:import org.json.JSONObjectclass Response(json: String) : JSONObject(json) {    val type: String? = this.optString("type")    val data = this.optJSONArray("data")            ?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject            ?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo}class Foo(json: String) : JSONObject(json) {    val id = this.optInt("id")    val title: String? = this.optString("title")}用法:val foos = Response(jsonString)


版权声明:本文为weixin_34452012原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。