1、依赖
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
2、解析
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主要构成部分
对应的类
data class Result(
val code: Int,
val message: String,
val data: Data
) : Serializable
- data部分的组成
对应的类:
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部分的组成
对应的类:
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)
原文地址:https://blog.csdn.net/weixin_74239923/article/details/134550424
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_2719.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。