[英]Parce complicated JSON object
我有復雜的 JSON object 作為響應。 我的意思是它包含子類。 所以我在想如何解析它。 我創建了數據 class:
@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) {
}
}
數據 Class
@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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.