build.gradle(app)中加入
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
var responseStr =
"{
"code": 200,
"message": "操作成功",
"data": {
"pageNum": 1,
"pageSize": 5,
"totalPage": 2,
"total": 8,
"list": [{
"id": 1,
"username": "test",
"password": "123",
"icon": "https://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/icon/github_icon_02.png",
"email": "[email protected]",
"nickName": "测试账号",
"note": null,
"createTime": "2018-09-29T05:55:30.000+00:00",
"loginTime": "2018-09-29T05:55:39.000+00:00",
"status": 1
}, {
"id": 3,
"username": "admin",
"password": "123",
"icon": "https://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/icon/github_icon_01.png",
"email": "[email protected]",
"nickName": "系统管理员",
"note": "系统管理员",
"createTime": "2018-10-08T05:32:47.000+00:00",
"loginTime": "2019-04-20T04:45:16.000+00:00",
"status": 1
}, {
"id": 4,
"username": "macro",
"password": "123",
"icon": "https://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/icon/github_icon_01.png",
"email": "[email protected]",
"nickName": "macro",
"note": "macro专用",
"createTime": "2019-10-06T07:53:51.000+00:00",
"loginTime": "2020-02-03T06:55:55.000+00:00",
"status": 1
}, {
"id": 6,
"username": "productAdmin",
"password": "123",
"icon": "https://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/icon/github_icon_03.png",
"email": "[email protected]",
"nickName": "商品管理员",
"note": "只有商品权限",
"createTime": "2020-02-07T08:15:08.000+00:00",
"loginTime": null,
"status": 1
}, {
"id": 7,
"username": "orderAdmin",
"password": "123",
"icon": "https://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/icon/github_icon_04.png",
"email": "[email protected]",
"nickName": "订单管理员",
"note": "只有订单管理权限",
"createTime": "2020-02-07T08:15:50.000+00:00",
"loginTime": null,
"status": 1
}]
}
}
data class Result(
val code: Int,
val message: String,
val data: Data
) : Serializable
data class Data(
val pageNum: Int,
val pageSize: Int,
val totalPage: Int,
val total: Int,
val list: List<list> = ArrayList(),
) : Serializable
Json中list使用[ ]
,所以这里的list写成: val list: List
= ArrayList()
data class list(
val id: Int,
val username: String,
val password: String,
val icon: String,
val email: String,
val nickName: String,
val createTime: String,
val loginTime: String,
val status: Int
) : Serializable
重点提醒:类里面的属性名必须跟Json字段里面的Key是一模一样的,否则会导致解析不成功
如果不一致:
这个部分我刚开始处理也错了,找了好久才发现,一定要注意
val gson = Gson()
val resultType = object : TypeToken<Result>() {}.type
val fromJson = gson.fromJson<Result>(responseStr, resultType)