android - Parce 复杂的 JSON 对象
问题描述
我有复杂的 JSON 对象作为响应。我的意思是它包含子类。所以我在想如何解析它。我创建了数据类:
@Parcelize
data class Attachments(
val photo:String,
val video:String,
val audio: audio,
val doc: doc,
val grafity: String,
val link: String,
val note: note,
val poll: poll,
val page: String
):Parcelable{
companion object :Parceler <Attachments>{
override fun create(parcel: Parcel): Attachments {
TODO("Not yet implemented")
}
override fun Attachments.write(parcel: Parcel, flags: Int) {
TODO("Not yet implemented")
}
}
}
子类也有类似的描述
那么,如何正确包裹它。我知道,我可以手动解析所有内容,但我为此寻找更优雅的方式。我想避免我在代码中感到困惑。
val response = r.getString("response") as String
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<WallJSON> =moshi.adapter(WallJSON::class.java)
val wallItem = jsonAdapter.fromJson(response)
适配器
class WallJSON() {
@FromJson fun WallFromJson(item: Wall) {
}
}
数据类
@Parcelize
@JsonClass(generateAdapter = true)
data class Wall (
val Text:String="",
val attachments: Attachments?,
):Parcelable
JSON
"response": {
"count": 8,
"items": [{
"id": 0,
"text": "",
"attachments": [{
"type": "photo",
"photo": {
"id": 00,
"post_id": 10064,
"height": 130,
"url": "https://",
"type": "m",
"width": 87
}, ],
"text": ""}}]
}
解决方案
使用一些 JSON 解析库(moshi、 gson 等)。并像这样更改您的类(moshi codegen 的示例):
@Parcelize
@JsonClass(generateAdapter = true)
data class Attachments(
val photo: String,
val video: String,
val audio: Audio,
val doc: Doc,
val grafity: String,
val link: String,
val note: Note,
val poll: Poll,
val page: String
) : Parcelable
@Parcelize
@JsonClass(generateAdapter = true)
data class Audio(
...
) : Parcelable
@Parcelize
@JsonClass(generateAdapter = true)
data class Doc(
...
) : Parcelable
等等
之后创建一个适配器并解析您的 json:
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(Attachments::class.java)
val attachments = adapter.fromJson(yourJson)
如果您的 json 是列表,请尝试使用此适配器:
val listType: Type = Types.newParameterizedType(
List::class.java,
Attachments::class.java
)
val listAdapter = moshi.adapter(listType)
val attachmentsList = listAdapter.fromJson(yourJson)
推荐阅读
- java - Java - Android Studio 中的网页抓取
- ruby-on-rails - 升级到 Rails 6 后出现 Coffee Script 编译语法错误
- apache-spark - Spark SQL - org.apache.spark.sql.AnalysisException
- javascript - 当两个数组中的 idItem 相同时选中复选框
- racket - 判决中的离奇合同违反
- php - 在静态方法的末尾调用另一个可选方法
- mysql - mysql LEFT JOIN 后跟 GROUP BY 与 BETWEEN 范围
- scheme - 将列表替换为列表列表
- javascript - 对象键已删除但仍在循环中迭代
- rxjs - 在分页期间从 springframework.data.repository.reactive.ReactiveCrudRepository 返回 Mono 时出现“不满足的依赖关系”异常