Skip to content
Advertisement

How to deserialize json to nested custom map via gson?

I have the following json

{
  "id": "1111",
  "match": {
    "username1": {
      "id": "1234",
      "name": "alex"
    },
    "username2": {
      "id": "5678",
      "name": "munch"
    }
  }
}

To deserialize it, I have the following data model class.

class json{
    String id;
    Match match;
}

class Match {  
  private Map<String,Profile> profiles  
}

class Profile{
    private String id;
    private String name;
}

I am not getting any deserialization error when I am using gson but the profiles variable is coming as null. This is how I am deserializing. var json = gson.fromJson(data,json.class)

inside the match object there can be a dynamic number of usernames not just two . Why am I getting profile object as null and how can I correctly populate it?

Making changes to json is the last resort here. I can make any other required changes.

Advertisement

Answer

The issue is your model. You don’t need Match because profiles does not really exist in your JSON. You just json (this one with small changes) and Profile:

class json{
    String id;
    Map<String,Profile> match;
}

This will work.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement