How to parse the Json response in android?

后端 未结 6 1809
一生所求
一生所求 2020-12-14 23:19

i m getting this response in a result of GET request to server

{\"LL\": { \"control\": \"dev/sys/getkey\", \"value\": \"4545453030304138303046392035343733373         


        
6条回答
  •  误落风尘
    2020-12-14 23:43

    Simple and Efficient solution : Use Googlle's Gson library

    • Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
    • Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.

    Type type = new TypeToken>(){}.getType();
    Map myMap = gson.fromJson(JsonString , type);
    

    or you can use this below class :

    To convert your JSON string to hashmap use this :

    HashMap hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
    

    Use this class :) (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;
        }
    }
    
    

    Thank me later :)

    提交回复
    热议问题