To iterate over the key-value pairs of a JSONObject
in Java, you can use the keys
method to get an iterator over the keys of the object, and then use the get
method to get the value for each key.
Here is an example of how you can iterate over the key-value pairs of a JSONObject
and print them:
JSONObject object = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}"); Iterator<String> iterator = object.keys(); while (iterator.hasNext()) { String key = iterator.next(); String value = object.getString(key); System.out.println(key + ": " + value); }
This will print the key-value pairs of the JSONObject
in the order they were added.
Keep in mind that the JSONObject
class is not thread-safe, so if multiple threads are accessing the object concurrently, you will need to synchronize access to the object to prevent race conditions.
You can also use the for-each
loop or the for
loop to iterate over the key-value pairs of a JSONObject
. Here is an example using the for-each
loop:
JSONObject object = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}"); for (String key : object.keySet()) { String value = object.getString(key); System.out.println(key + ": " + value); }
And here is an example using the for
loop:
JSONObject object = new JSONObject("{\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}"); String[] keys = object.keySet().toArray(new String[0]); for (int i = 0; i < keys.length; i++) { String key = keys[i]; String value = object.getString(key); System.out.println(key + ": " + value); }