W3docs

How to iterate over a JSONObject?

To iterate over the key/value pairs in a JSONObject, you can use the keys method to get an iterator over the keys in the object, and then use the get method to get the value for each key.

To iterate over the key/value pairs in a JSONObject, you can use the keys method to get an iterator over the keys in the object, and then use the get method to get the value for each key. Here's an example of how you can iterate over a JSONObject in Java:


import org.json.JSONObject;
import java.util.Iterator;
import org.json.JSONException;

try {
    JSONObject obj = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\"}");

    Iterator<String> keys = obj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        Object value = obj.get(key);
        System.out.println(key + ": " + value);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

This will print the key/value pairs of the JSONObject to the console.

You can also use the names method to get a JSONArray of keys, which you can then iterate over using a standard for loop:


import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

try {
    JSONObject obj = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\"}");

    JSONArray keys = obj.names();
    for (int i = 0; i < keys.length(); i++) {
        String key = keys.getString(i);
        Object value = obj.get(key);
        System.out.println(key + ": " + value);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

This will also print the key/value pairs of the JSONObject to the console.

Note: org.json.JSONObject does not implement java.util.Map, so keySet() and entrySet() are not available. If you need entrySet() iteration, consider using a Map-based library like Gson (com.google.gson.JsonObject). Additionally, keys() returns an Iterator<String> in org.json version 20210517 and later; older versions return a JSONArray.