How to iterate over a JSONObject?

后端 未结 16 1877
孤街浪徒
孤街浪徒 2020-11-22 04:17

I use a JSON library called JSONObject (I don\'t mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSO

16条回答
  •  悲哀的现实
    2020-11-22 04:32

    Below code worked fine for me. Please help me if tuning can be done. This gets all the keys even from the nested JSON objects.

    public static void main(String args[]) {
        String s = ""; // Sample JSON to be parsed
    
        JSONParser parser = new JSONParser();
        JSONObject obj = null;
        try {
            obj = (JSONObject) parser.parse(s);
            @SuppressWarnings("unchecked")
            List parameterKeys = new ArrayList(obj.keySet());
            List  result = null;
            List keys = new ArrayList<>();
            for (String str : parameterKeys) {
                keys.add(str);
                result = this.addNestedKeys(obj, keys, str);
            }
            System.out.println(result.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    public static List addNestedKeys(JSONObject obj, List keys, String key) {
        if (isNestedJsonAnArray(obj.get(key))) {
            JSONArray array = (JSONArray) obj.get(key);
            for (int i = 0; i < array.length(); i++) {
                try {
                    JSONObject arrayObj = (JSONObject) array.get(i);
                    List list = new ArrayList<>(arrayObj.keySet());
                    for (String s : list) {
                        putNestedKeysToList(keys, key, s);
                        addNestedKeys(arrayObj, keys, s);
                    }
                } catch (JSONException e) {
                    LOG.error("", e);
                }
            }
        } else if (isNestedJsonAnObject(obj.get(key))) {
            JSONObject arrayObj = (JSONObject) obj.get(key);
            List nestedKeys = new ArrayList<>(arrayObj.keySet());
            for (String s : nestedKeys) {
                putNestedKeysToList(keys, key, s);
                addNestedKeys(arrayObj, keys, s);
            }
        }
        return keys;
    }
    
    private static void putNestedKeysToList(List keys, String key, String s) {
        if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
            keys.add(key + Constants.JSON_KEY_SPLITTER + s);
        }
    }
    
    
    
    private static boolean isNestedJsonAnObject(Object object) {
        boolean bool = false;
        if (object instanceof JSONObject) {
            bool = true;
        }
        return bool;
    }
    
    private static boolean isNestedJsonAnArray(Object object) {
        boolean bool = false;
        if (object instanceof JSONArray) {
            bool = true;
        }
        return bool;
    }
    

提交回复
热议问题