How to iterate over a JSONObject?

后端 未结 16 1889
孤街浪徒
孤街浪徒 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:49

    I once had a json that had ids that needed to be incremented by one since they were 0-indexed and that was breaking Mysql auto-increment.

    So for each object I wrote this code - might be helpful to someone:

    public static void  incrementValue(JSONObject obj, List keysToIncrementValue) {
            Set keys = obj.keySet();
            for (String key : keys) {
                Object ob = obj.get(key);
    
                if (keysToIncrementValue.contains(key)) {
                    obj.put(key, (Integer)obj.get(key) + 1);
                }
    
                if (ob instanceof JSONObject) {
                    incrementValue((JSONObject) ob, keysToIncrementValue);
                }
                else if (ob instanceof JSONArray) {
                    JSONArray arr = (JSONArray) ob;
                    for (int i=0; i < arr.length(); i++) {
                        Object arrObj = arr.get(0);
                        if (arrObj instanceof JSONObject) {
                            incrementValue((JSONObject) arrObj, keysToIncrementValue);
                        }
                    }
                }
            }
        }
    

    usage:

    JSONObject object = ....
    incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
    

    this can be transformed to work for JSONArray as parent object too

提交回复
热议问题