Convert JSONObject to Map

后端 未结 6 1906
抹茶落季
抹茶落季 2020-12-08 18:20

I have a JSONObject with some attributes that I want to convert into a Map

Is there something that I can use from the

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 19:10

    This is what worked for me:

        public static Map toMap(JSONObject jsonobj)  throws JSONException {
            Map map = new HashMap();
            Iterator keys = jsonobj.keys();
            while(keys.hasNext()) {
                String key = keys.next();
                Object value = jsonobj.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;
    }
    
    
    

    Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

    提交回复
    热议问题