首页 > 解决方案 > 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": ""}}]    

    }

标签: androidjsonkotlin

解决方案


使用一些 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)

推荐阅读