简体   繁体   中英

Parce complicated JSON object

I`ve got complicated JSON object as response. I mean what it contains subclasses. So I thinking how parse it. I created data 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")
      }

   }

}

subclasses are also described similarly

So, how to parcel it correct. I know, that I can parse all it by manual, but I searching for more elegant way for this. I want to avoid that I get confused in the code.

 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)

Adapter

class WallJSON() {

    @FromJson fun WallFromJson(item: Wall) {

    }
}

Data 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": ""}}]    

    }

Use some of JSON parsing libraries ( moshi , gson etc). And change your classes like these (example for 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

etc.

After that create an adapter and parse your json:

val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(Attachments::class.java)
val attachments = adapter.fromJson(yourJson)

If your json is list, try this adapter:

val listType: Type = Types.newParameterizedType(
    List::class.java,
    Attachments::class.java
)
val listAdapter = moshi.adapter(listType)
val attachmentsList = listAdapter.fromJson(yourJson)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM