Home > Java > javaTutorial > How Do I Iterate Over a JSONObject in Java?

How Do I Iterate Over a JSONObject in Java?

Barbara Streisand
Release: 2024-12-17 20:50:11
Original
636 people have browsed it

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
   }
}
Copy after login

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      
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template