How can I convert JSON to a HashMap using Gson?

前端 未结 16 2642
臣服心动
臣服心动 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 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 _jsonToMap_(JSONObject json) throws JSONException {
            Map retMap = new HashMap();
    
            if(json != JSONObject.NULL) {
                retMap = toMap(json);
            }
            return retMap;
        }
    
    
        private static Map toMap(JSONObject object) throws JSONException {
            Map map = new HashMap();
    
            Iterator 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 toList(JSONArray array) throws JSONException {
            List list = new ArrayList();
            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 hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
    

    提交回复
    热议问题