How to iterate over a JSONObject?

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

    I will avoid iterator as they can add/remove object during iteration, also for clean code use for loop. it will be simply clean & fewer lines.

    Using Java 8 and Lamda [Update 4/2/2019]

    import org.json.JSONObject;
    
    public static void printJsonObject(JSONObject jsonObj) {
        jsonObj.keySet().forEach(keyStr ->
        {
            Object keyvalue = jsonObj.get(keyStr);
            System.out.println("key: "+ keyStr + " value: " + keyvalue);
    
            //for nested objects iteration if required
            //if (keyvalue instanceof JSONObject)
            //    printJsonObject((JSONObject)keyvalue);
        });
    }
    

    Using old way [Update 4/2/2019]

    import org.json.JSONObject;
    
    public static void printJsonObject(JSONObject jsonObj) {
        for (String keyStr : jsonObj.keySet()) {
            Object keyvalue = jsonObj.get(keyStr);
    
            //Print key and value
            System.out.println("key: "+ keyStr + " value: " + keyvalue);
    
            //for nested objects iteration if required
            //if (keyvalue instanceof JSONObject)
            //    printJsonObject((JSONObject)keyvalue);
        }
    }
    

    Original Answer

    import org.json.simple.JSONObject;
    public static void printJsonObject(JSONObject jsonObj) {
        for (Object key : jsonObj.keySet()) {
            //based on you key types
            String keyStr = (String)key;
            Object keyvalue = jsonObj.get(keyStr);
    
            //Print key and value
            System.out.println("key: "+ keyStr + " value: " + keyvalue);
    
            //for nested objects iteration if required
            if (keyvalue instanceof JSONObject)
                printJsonObject((JSONObject)keyvalue);
        }
    }
    

提交回复
热议问题