How to iterate over a JSONObject?

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

    Most of the answers here are for flat JSON structures, in case you have a JSON which might have nested JSONArrays or Nested JSONObjects, the real complexity arises. The following code snippet takes care of such a business requirement. It takes a hash map, and hierarchical JSON with both nested JSONArrays and JSONObjects and updates the JSON with the data in the hash map

    public void updateData(JSONObject fullResponse, HashMap mapToUpdate) {
    
        fullResponse.keySet().forEach(keyStr -> {
            Object keyvalue = fullResponse.get(keyStr);
    
            if (keyvalue instanceof JSONArray) {
                updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
            } else if (keyvalue instanceof JSONObject) {
                updateData((JSONObject) keyvalue, mapToUpdate);
            } else {
                // System.out.println("key: " + keyStr + " value: " + keyvalue);
                if (mapToUpdate.containsKey(keyStr)) {
                    fullResponse.put(keyStr, mapToUpdate.get(keyStr));
                }
            }
        });
    
    }
    

    You have to notice here that the return type of this is void, but sice objects are passed as refernce this change is refelected to the caller.

提交回复
热议问题