文章目录
1、依赖
build.gradle(app)中加入
java
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
2、解析
- 假设这是要解析Json数据
java
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": "test@qq.com",
"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": "admin@163.com",
"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": "macro@qq.com",
"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": "product@qq.com",
"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": "order@qq.com",
"nickName": "订单管理员",
"note": "只有订单管理权限",
"createTime": "2020-02-07T08:15:50.000+00:00",
"loginTime": null,
"status": 1
}]
}
}
- 分析Json的结构
- Json主要构成部分
对应的类
kotlin
data class Result(
val code: Int,
val message: String,
val data: Data
) : Serializable
- data部分的组成
对应的类:
kotlin
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<list> = ArrayList()
- list部分的组成
对应的类:
kotlin
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是一模一样的,否则会导致解析不成功
如果不一致:
这个部分我刚开始处理也错了,找了好久才发现,一定要注意
- 开始解析
kotlin
val gson = Gson()
val resultType = object : TypeToken<Result>() {}.type
val fromJson = gson.fromJson<Result>(responseStr, resultType)
- 提取数据
通过fromJson
提取
如: