How to iterate over a JSONObject?

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

    for my case i found iterating the names() works well

    for(int i = 0; i<jobject.names().length(); i++){
        Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
    }
    
    0 讨论(0)
  • 2020-11-22 04:54

    With Java 8 and lambda, cleaner:

    JSONObject jObject = new JSONObject(contents.trim());
    
    jObject.keys().forEachRemaining(k ->
    {
    
    });
    

    https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-

    0 讨论(0)
  • 2020-11-22 04:54

    This is is another working solution to the problem:

    public void test (){
    
        Map<String, String> keyValueStore = new HasMap<>();
        Stack<String> keyPath = new Stack();
        JSONObject json = new JSONObject("thisYourJsonObject");
        keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
        for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
            System.out.println(map.getKey() + ":" + map.getValue());
        }   
    }
    
    public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
        Set<String> jsonKeys = json.keySet();
        for (Object keyO : jsonKeys) {
            String key = (String) keyO;
            keyPath.push(key);
            Object object = json.get(key);
    
            if (object instanceof JSONObject) {
                getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
            }
    
            if (object instanceof JSONArray) {
                doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
            }
    
            if (object instanceof String || object instanceof Boolean || object.equals(null)) {
                String keyStr = "";
    
                for (String keySub : keyPath) {
                    keyStr += keySub + ".";
                }
    
                keyStr = keyStr.substring(0, keyStr.length() - 1);
    
                keyPath.pop();
    
                keyValueStore.put(keyStr, json.get(key).toString());
            }
        }
    
        if (keyPath.size() > 0) {
            keyPath.pop();
        }
    
        return keyValueStore;
    }
    
    public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
            String key) {
        JSONArray arr = (JSONArray) object;
        for (int i = 0; i < arr.length(); i++) {
            keyPath.push(Integer.toString(i));
            Object obj = arr.get(i);
            if (obj instanceof JSONObject) {
                getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
            }
    
            if (obj instanceof JSONArray) {
                doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
            }
    
            if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
                String keyStr = "";
    
                for (String keySub : keyPath) {
                    keyStr += keySub + ".";
                }
    
                keyStr = keyStr.substring(0, keyStr.length() - 1);
    
                keyPath.pop();
    
                keyValueStore.put(keyStr , json.get(key).toString());
            }
        }
        if (keyPath.size() > 0) {
            keyPath.pop();
        }
    }
    
    0 讨论(0)
  • 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<String, String> 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.

    0 讨论(0)
提交回复
热议问题