gpt4 book ai didi

java - Gson反序列化为 map

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:15:05 25 4
gpt4 key购买 nike

我有这个 json 字符串,我需要将其反序列化为 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"
}
}
]

所以字符串应该是键,然后值应该是它所代表的对象。我有一个为 UUID 对象编写的自定义解串器,它已经过测试并且可以工作(所以这不是问题所在)。

编辑:

我找到了一个更好的 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
}
}

最佳答案

首先,将 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> 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));

关于java - Gson反序列化为 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24765039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com