Java Gson反序列化成地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24765039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gson deserialize into map
提问by TomShar
I have this json string which I need to get deserialized into a map: Map
我有这个 json 字符串,我需要将其反序列化为地图: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).
所以字符串应该是键,然后值应该是它所代表的对象。我有一个为 UUID 对象编写的自定义 deseriaziler 并且经过测试和工作(所以这不是问题)。
EDIT:
编辑:
I found a better JSON structure I can use for my problem that works exactly how I want it to.
我找到了一个更好的 JSON 结构,我可以用它来解决我的问题,它完全符合我的要求。
"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
}
}
采纳答案by Braj
First, enclose the JSON string inside {...}
, then you can easily convert it into Map as shown below:
首先,将 JSON 字符串括在 中{...}
,然后您可以轻松地将其转换为 Map,如下所示:
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?
是否有可能拥有这样的地图:
Map<String, PlayerObject>
玩家?
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));