Iterate through JSONObject from root in json simple

天大地大妈咪最大 提交于 2019-12-02 18:08:43

Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:

JSONParser parser = new JSONParser();

Object obj = parser.parse(new FileReader("simple.json"));

JSONObject jsonObject = (JSONObject) obj;

for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(jsonObject.get(key));
}
Ratnesh Kumar

You can do like this

String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
    String key = (String)keys.next();
    if ( resobj.get(key) instanceof JSONObject ) {
        JSONObject xx = new JSONObject(resobj.get(key).toString());
        Log.d("res1",xx.getString("something"));
        Log.d("res2",xx.getString("something2"));
    }
}

In Java 8 we can use lambdas

void handleJSONObject(JSONObject jsonObject) {
jsonObject.keys().forEachRemaining(key -> {
    Object value = jsonObject.get(key);
    logger.info("Key: {0}\tValue: {1}", key, value);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!