Kotlin 解析json

时间:2025-03-29 08:55:36

背景

{
    "status": 1,
    "data": {
        "id": 52,
        "userName": "admin",
        "createTime": "2021-11-03 15:12:46",
        "updateTime": "2021-11-03 15:12:46"
    },
    "msg": "登录成功"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

针对这种嵌套数据

解决

封装对象

import .*

class UserVo {
    var userId: Int? = null
    var userName: String? = null
    var createTime: String? = null
    var updateTime: String? = null
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
package 

import 

class ServerResponse <T>{
     var status: Int = -1
     var data: T? = null  //status为0时,将返回的数据封装到data
     var msg: String? = null  //提示信息
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

需要依赖

implementation ':gson:2.8.5'
  • 1
import 
  • 1

解析

  val turnsType = object : TypeToken<ServerResponse<UserVo>>() {}.type
  val jsobj = Gson().fromJson<ServerResponse<UserVo>>(result, turnsType)
  • 1
  • 2

此时即解析出ServerResponse也解析出UserVo

针对不解析嵌套对象的情况使用如下方式就可

var jsobj = Gson().fromJson(result, ServerResponse::)
  • 1