
慕用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)
该博客展示了如何在Android环境中,不依赖外部库,使用Kotlin解析JSON字符串并将其转化为自定义对象。通过创建`Response`和`Foo`类,将JSON数据映射为可操作的对象,便于数据处理和业务逻辑。示例代码详细解释了转换过程。
1175

被折叠的 条评论
为什么被折叠?



