Gson反序列化为地图

时间:2014-07-15 17:59:56

标签: java json map gson deserialization

我有这个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
    }
}

1 个答案:

答案 0 :(得分:11)

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

是否可以将地图设为:Map<String, PlayerObject>玩家?

是的,您可以将其转换为所需的格式,如下所示:

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));