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. Here's an example of how you can iterate over a JSONObject in Java:

import org.json.JSONObject;

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

for (String key : obj.keySet()) {
  Object value = obj.get(key);
  System.out.println(key + ": " + value);
}

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

You can also use the entrySet method to get a set of Map.Entry objects, which you can then iterate over using a for loop:

import org.json.JSONObject;

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

for (Map.Entry<String, Object> entry : obj.entrySet()) {
  String key = entry.getKey();
  Object value = entry.getValue();
  System.out.println(key + ": " + value);
}

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