java – Gson反序列化为map

我有这个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对象编写的自定义deseriaziler,并且经过测试和工作(这不是问题).

编辑:

我找到了一个更好的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 - 代码日志