What is the method for iterating through a JsonObject in Java?
In Java, you can use the keys() method of JSONObject to retrieve all its keys, and then use the get() method to access the corresponding value based on the key.
Here is an example code:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
// 遍历JSONObject的所有key
for (String key : jsonObject.keys()) {
// 根据key获取对应的value
Object value = jsonObject.get(key);
System.out.println("Key: " + key);
System.out.println("Value: " + value);
}
}
}
Output result:
Key: name
Value: John
Key: age
Value: 30
Key: city
Value: New York
During the process of traversal, we can handle the key and value accordingly as needed.