How to iterate over a JSONObject?
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); }}