gpt4 book ai didi

android - 解析复杂的JSON对象

转载 作者:行者123 更新时间:2023-12-02 13:17:35 26 4
gpt4 key购买 nike

我有复杂的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)

关于android - 解析复杂的JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62277849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com