Reputation: 97
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": ""}}]
}
Upvotes: 1
Views: 1039
Reputation: 6426
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)
Upvotes: 2