android - 解析复杂的JSON对象

标签 android json kotlin

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

相关文章:

Android 应用程序在我安装后无法打开。但它可以在模拟器中运行

javascript - React Native - 如何 trim 字符串

javascript - 为 AJAX JSON 调用创建 for-loop/.each 循环

javascript - 将 JSON 传递到循环中

android-studio - 如何降级 Kotlin 版本

android - 如何立即开始执行 Kotlin Coroutine

android - 在 listView 之前调用 onTouchEvent()

android - 使用 android-gradle 3 在 Android 库中公开支持库依赖项的正确方法是什么?

javascript - 使用 Ember.js 在模板中显示模型 JSON 数据

android - 如何根据 mockk 中传递的参数从同一函数返回两个不同的模拟?