Dynamic naming SerializedName top-level object with GSON

Issue

I am new to programming. I have an app that retrieves json data from api using retrofit but I have small issue, json response contains dynamic top-level object:

sample.json:

{
  "ISBN:0-7868-5629-7": {
    "bib_key": "ISBN:0-7868-5629-7",
    "info_url": "https://openlibrary.org/books/OL25747413M/The_Lightning_Thief",
    "preview": "borrow",
    "preview_url": "https://archive.org/details/lightningthief0000rior_u3l0",
    "thumbnail_url": "https://covers.openlibrary.org/b/id/7357496-S.jpg",
    "details": {...}
  }
}

JSONModel.kt:

...
data class JSONModel(
    @SerializedName("...") //<-- don't know how to annotate, should contain ISBN:<ISBN number>
    @Expose
    val isbn: ISBNModel
)

How can I annotate dynamic top-level json object in this case?

Update
It seems like Gson is failing to deserialize without using @SerializedName(…) annotation, I used static value to check and it worked. After I remove the annotation, response body is null. Is this annotation required?

Solution

Removing JSONModel data class and using Map<String, ISBNModel> instead solved the problem as it was mentioned by @Marcono1234

In my case, as I am using retrofit:

...
call.enqueue(object : Callback<Map<String, ISBNModel> { ... })
...

this will solve it

Answered By – Javokhir Matnazarov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published