2

I am using Retrofit and Gson to query an API, however I have never come across a JSON response like it.

The Response:

{
    Response: {
        "Black":[
            {"id":"123","code":"RX766"},
            {"id":"324","code":"RT344"}],
        "Green":[
            {"id":"3532","code":"RT983"},
            {"id":"242","code":"RL982"}],
        "Blue":[
            {"id":"453","code":"RY676"},
            {"id":"134","code":"R67HJH"}]
    }
}

The problem is the list elements id eg "black" is dynamic, so I a have no idea what they will be.

So far I have created a class for the inner type;

class Type {
    @SerializedName("id") private String id;
    @SerializedName("code") private String code;
}

Is it possible to have the following?

class Response {

    @SerializedName("response")
    List<Type> types;
}

And then move the list ID into the type, so the Type class would become;

class Type {
    @SerializedName("id") private String id;
    @SerializedName("code") private String code;
    @SerializedName("$") private String type; //not sure how this would be populated
}

If not, how else could this be parsed with just Gson attributes?

Ok so I have just seen this question; How to parse dynamic JSON fields with GSON?

which looks great, is it possible to wrap a generic map with the response object?

Community
  • 1
  • 1
Lunar
  • 4,663
  • 7
  • 43
  • 51

1 Answers1

5

If the keys are dynamic you want a map.

class Response {
    @SerializedName("response")
    Map<String, List<Type>> types;
}

After deserialization you can coerce the types into something more semantic in your domain.

If this is not suitable you will need to register a TypeAdapter or a JsonDeserializer and do custom deserialization of the map-like data into a simple List.

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • @Jake Could u please help for following parsing, mentioned [here](http://stackoverflow.com/q/33758601/2624806) – CoDe Nov 17 '15 at 13:55