How can I convert JSON to a HashMap using Gson?

前端 未结 16 2331
臣服心动
臣服心动 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:03

    You can use this class instead :) (handles even lists , nested lists and json)

    public class Utility {
    
        public static Map<String, Object> jsonToMap(Object json) throws JSONException {
    
            if(json instanceof JSONObject)
                return _jsonToMap_((JSONObject)json) ;
    
            else if (json instanceof String)
            {
                JSONObject jsonObject = new JSONObject((String)json) ;
                return _jsonToMap_(jsonObject) ;
            }
            return null ;
        }
    
    
       private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
            Map<String, Object> retMap = new HashMap<String, Object>();
    
            if(json != JSONObject.NULL) {
                retMap = toMap(json);
            }
            return retMap;
        }
    
    
        private static Map<String, Object> toMap(JSONObject object) throws JSONException {
            Map<String, Object> map = new HashMap<String, Object>();
    
            Iterator<String> keysItr = object.keys();
            while(keysItr.hasNext()) {
                String key = keysItr.next();
                Object value = object.get(key);
    
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                map.put(key, value);
            }
            return map;
        }
    
    
        public static List<Object> toList(JSONArray array) throws JSONException {
            List<Object> list = new ArrayList<Object>();
            for(int i = 0; i < array.length(); i++) {
                Object value = array.get(i);
                if(value instanceof JSONArray) {
                    value = toList((JSONArray) value);
                }
    
                else if(value instanceof JSONObject) {
                    value = toMap((JSONObject) value);
                }
                list.add(value);
            }
            return list;
        }
    }
    

    To convert your JSON string to hashmap use this :

    HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
    
    0 讨论(0)
  • 2020-11-22 06:05

    Here is what I have been using:

    public static HashMap<String, Object> parse(String json) {
        JsonObject object = (JsonObject) parser.parse(json);
        Set<Map.Entry<String, JsonElement>> set = object.entrySet();
        Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
        HashMap<String, Object> map = new HashMap<String, Object>();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonElement> 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;
    }
    
    0 讨论(0)
  • 2020-11-22 06:09

    With google's Gson 2.7 (probably earlier versions too, but I tested with the current version 2.7) it's as simple as:

    Map map = gson.fromJson(jsonString, Map.class);
    

    Which returns a Map of type com.google.gson.internal.LinkedTreeMap and works recursively on nested objects, arrays, etc.

    I ran the OP example like so (simply replaced double- with single-quotes and removed whitespace):

    String jsonString = "{'header': {'alerts': [{'AlertID': '2', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}, {'AlertID': '3', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}], 'session': '0bc8d0835f93ac3ebbf11560b2c5be9a'}, 'result': '4be26bc400d3c'}";
    Map map = gson.fromJson(jsonString, Map.class);
    System.out.println(map.getClass().toString());
    System.out.println(map);
    

    And got the following output:

    class com.google.gson.internal.LinkedTreeMap
    {header={alerts=[{AlertID=2, TSExpires=null, Target=1, Text=woot, Type=1}, {AlertID=3, TSExpires=null, Target=1, Text=woot, Type=1}], session=0bc8d0835f93ac3ebbf11560b2c5be9a}, result=4be26bc400d3c}
    
    0 讨论(0)
  • 2020-11-22 06:10

    I used this code:

    Gson gson = new Gson();
    HashMap<String, Object> fields = gson.fromJson(json, HashMap.class);
    
    0 讨论(0)
提交回复
热议问题