What is the method for traversing a JSONObject in Android?
In Android, you can use the JSONObject.keys() method to iterate through all key-value pairs in a JSONObject.
The sample code is shown below:
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do something with key and value
}
In the example above, jsonString is a string containing JSON data. We start by creating a JSONObject object, then use the keys() method to get all the keys of key-value pairs, and finally use the getString() method to get the corresponding value based on the key. We can then process each key-value pair’s data within a while loop.