Android JSONObject - How can I loop through a flat JSON object to get each key and value

JavaAndroidJson

Java Problem Overview


{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

How I can get each item's key and value without knowing the key nor value beforehand?

Java Solutions


Solution 1 - Java

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

Solution 2 - Java

Short version of Franci's answer:

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    ...
}

Solution 3 - Java

You'll need to use an Iterator to loop through the keys to get their values.

Here's a Kotlin implementation, you will realised that the way I got the string is using optString(), which is expecting a String or a nullable value.

val keys = jsonObject.keys()
while (keys.hasNext()) {
    val key = keys.next()
    val value = targetJson.optString(key)        
}

Solution 4 - Java

You shold use the keys() or names() method. keys() will give you an iterator containing all the String property names in the object while names() will give you an array of all key String names.

You can get the JSONObject documentation here

http://developer.android.com/reference/org/json/JSONObject.html

Solution 5 - Java

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1763763View Question on Stackoverflow
Solution 1 - JavaFranci PenovView Answer on Stackoverflow
Solution 2 - JavaRoozbeh ZabihollahiView Answer on Stackoverflow
Solution 3 - JavaMorgan KohView Answer on Stackoverflow
Solution 4 - JavaMike BrantView Answer on Stackoverflow
Solution 5 - JavaTomView Answer on Stackoverflow