Home > front end >  How to deserialize json to nested custom map via gson?
How to deserialize json to nested custom map via gson?

Time:11-12

I have the following json

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

To deserialise 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 deserialisation 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 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.

CodePudding user response:

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.

  • Related