Home > Software design >  How to deserialize the string with nondeterministic keys using gson?
How to deserialize the string with nondeterministic keys using gson?

Time:03-14

I have a JSON string in which the keys are not predictable. The server returns the values with different keys with each response. Sample JSON looks like -

{
    "ids": {
        "123": "08:10",
        "456": "08:00"
    }
}

Here, keys 123 and 345 are not fixed i.e. on the next request, my response would look as below -

{
    "ids": {
        "123": "08:10",
        "456": "08:00"
    }
}

Now, I want to parse this response into an object using GSON. So, I created the model classes as below -

data class SlotsResponse(
    val ids: IDs
)

data class IDs(
    val id: Map<String, String>
)

And in the code, I am trying to deserialize it as -

val response = Gson().fromJson(strResponse, SlotsResponse::class.java)

But, I am unable to get the values for IDs. They are null.

Can someone please help me to understand whatever I am trying to achieve is possible?

CodePudding user response:

What you have represented with your current model contains one extra nested object. So it would represent JSONs that look like this:

{
    "ids": {
        "id": {
            "123": "08:10",
            "456": "08:00"
        }
    }
}

In your actual JSON, there is no field named id, so you only need the root object with the field ids, and the dynamic map:

data class SlotsResponse(
    val ids: Map<String, String>
)
  • Related