TomShar TomShar - 3 months ago 23
Java Question

Gson deserialize into map

I have this json string which I need to get deserialized into a map: Map

"players_test": [
{
"54231f85f8e049c7bd8ac0aba3d1caf7": {
"uuid": "54231f85f8e049c7bd8ac0aba3d1caf7",
"name": "TomShar",
"signup_time": "2014-07-04 16:27:16"
}
},
{
"54231f85f8e049c7bd8ac0aba3d1caf7": {
"uuid": "54231f85f8e049c7bd8ac0aba3d1caf7",
"name": "TomShar",
"signup_time": "2014-07-04 16:27:16"
}
},
{
"54231f85f8e049c7bd8ac0aba3d1caf7": {
"uuid": "54231f85f8e049c7bd8ac0aba3d1caf7",
"name": "TomShar",
"signup_time": "2014-07-04 16:27:16"
}
}
]


So the Strings should be the keys and then the value should be of the object it represents. I have a custom deseriaziler written for the UUID object and that is tested and works (so that isn't the problem).

EDIT:

I found a better JSON structure I can use for my problem that works exactly how I want it to.

"players": {
"54231f85-f8e0-49c7-bd8a-c0aba3d1caf7": {
"uuid": "54231f85-f8e0-49c7-bd8a-c0aba3d1caf7",
"name": "TomShar",
"kills": 0,
"assists": 0,
"damage_dealt": 0,
"time_alive": 0,
"dead": false
},
"KEY": {
"uuid": "KEY",
"name": "Name",
"kills": 0,
"assists": 0,
"damage_dealt": 0,
"time_alive": 0,
"dead": false
},
"KEY": {
"uuid": "KEY",
"name": "Name",
"kills": 0,
"assists": 0,
"damage_dealt": 0,
"time_alive": 0,
"dead": false
}
}

Answer

First, enclose the JSON string inside {...}, then you can easily convert it into Map as shown below:

class PlayerObject {
    private String uuid;
    private String name;
    private String signup_time;
    // getters & setters
}

Gson gson = new Gson();
Type type = new TypeToken<Map<String, ArrayList<Map<String, PlayerObject>>>>(){}.getType();
Map<String, ArrayList<Map<String, PlayerObject>>> map = gson.fromJson(jsonString, type);

Is it possible to have the map like: Map<String, PlayerObject> players?

Yes, you can convert it into desired format as shown below:

Map<String,PlayerObject> players=new HashMap<String,PlayerObject>();
for(Map<String, PlayerObject> m:map.get("players_test")){
   for(String key:m.keySet()){
       players.put(key, m.get(key));
   }
}
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(players));
Comments