我将避免迭代器,因为它们可以在迭代期间添加/删除对象,也可以用于循环的干净代码。它将是简单的干净&较少的线条。
使用Java 8和Lamda[更新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);
});}
使用旧方法[更新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);
}}
原始答案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);
}}