How can I convert JSON to a HashMap using Gson?

前端 未结 16 2567
臣服心动
臣服心动 2020-11-22 05:14

I\'m requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn\'t hard at all but the other way seems to

16条回答
  •  没有蜡笔的小新
    2020-11-22 06:05

    Here is what I have been using:

    public static HashMap parse(String json) {
        JsonObject object = (JsonObject) parser.parse(json);
        Set> set = object.entrySet();
        Iterator> iterator = set.iterator();
        HashMap map = new HashMap();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            if (!value.isJsonPrimitive()) {
                map.put(key, parse(value.toString()));
            } else {
                map.put(key, value.getAsString());
            }
        }
        return map;
    }
    

提交回复
热议问题