Home >Java >javaTutorial >How Do I Iterate Over a JSONObject in Java?
Iterating Over a JSONObject
You may encounter situations where you need to iterate over a JSONObject instead of a JSONArray. This can occur when working with data structures like those obtained from Facebook. While accessing elements of a JSONArray using indexes is straightforward, accessing elements of a JSONObject in the same manner is not immediately apparent. This article presents a concise solution to this challenge.
To iterate over a JSONObject, you can utilize the combination of the keys() and get() methods. The keys() method returns an iterator for the keys of the JSONObject. You can then iterate over the keys and retrieve the corresponding values using the get() method.
Consider the following example JSONObject:
{ "http://http://url.com/": { "id": "http://http://url.com//" }, "http://url2.co/": { "id": "http://url2.com//", "shares": 16 } , "http://url3.com/": { "id": "http://url3.com//", "shares": 16 } }
To iterate over this JSONObject, you can use the following code:
JSONObject jsonObject = new JSONObject(contents.trim()); Iterator<String> keys = jsonObject.keys(); while(keys.hasNext()) { String key = keys.next(); if (jsonObject.get(key) instanceof JSONObject) { // do something with jsonObject here } }
The above is the detailed content of How Do I Iterate Over a JSONObject in Java?. For more information, please follow other related articles on the PHP Chinese website!