How can I convert JSON to a HashMap using Gson?

前端 未结 16 2566
臣服心动
臣服心动 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 05:57

    Try this, it will worked. I used it for Hashtable.

    public static Hashtable parseModifued(String json) {
        JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(json);
        Set> set = object.entrySet();
        Iterator> iterator = set.iterator();
    
        Hashtable map = new Hashtable();
    
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
    
            Integer key = Integer.parseInt(entry.getKey());
            KioskStatusResource value = new Gson().fromJson(entry.getValue(), KioskStatusResource.class);
    
            if (value != null) {
                map.put(key, value);
            }
    
        }
        return map;
    }
    

    Replace KioskStatusResource to your class and Integer to your key class.

提交回复
热议问题