背景
{
"status": 1,
"data": {
"id": 52,
"userName": "admin",
"createTime": "2021-11-03 15:12:46",
"updateTime": "2021-11-03 15:12:46"
},
"msg": "登录成功"
}
针对这种嵌套数据
解决
封装对象
import java.util.*
class UserVo {
var userId: Int? = null
var userName: String? = null
var createTime: String? = null
var updateTime: String? = null
}
package com.lettytrain.notesapp.vo
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
class ServerResponse <T>{
var status: Int = -1
var data: T? = null //status为0时,将返回的数据封装到data
var msg: String? = null //提示信息
}
需要依赖
implementation 'com.google.code.gson:gson:2.8.5'
import com.google.gson.Gson
解析
val turnsType = object : TypeToken<ServerResponse<UserVo>>() {}.type
val jsobj = Gson().fromJson<ServerResponse<UserVo>>(result, turnsType)
此时即解析出ServerResponse也解析出UserVo
针对不解析嵌套对象的情况使用如下方式就可
var jsobj = Gson().fromJson(result, ServerResponse::class.java)
Kotlin高效解析JSON实战
本文介绍了在Kotlin中解析嵌套JSON数据的方法,包括如何封装对象和依赖库的使用,详细展示了如何解析ServerResponse及其中的UserVo对象,同时提供了简化解析非嵌套对象的技巧。
1157

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



