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

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

Morgan Koh
  • 2,297
  • 24
  • 24
user1763763
  • 1,143
  • 2
  • 8
  • 8

5 Answers5

326

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!
    }
}
Ethan
  • 4,295
  • 4
  • 25
  • 44
Franci Penov
  • 74,861
  • 18
  • 132
  • 169
69

Short version of Franci's answer:

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    ...
}
Roozbeh Zabihollahi
  • 7,207
  • 45
  • 39
8

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)        
}
Morgan Koh
  • 2,297
  • 24
  • 24
3

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

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
-2

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.

Tom
  • 2,973
  • 3
  • 28
  • 32
  • 1
    Wrong link. The `JSONObject` in Android doesn't have `getNames()`. http://developer.android.com/reference/org/json/JSONObject.html – Weetu Oct 29 '15 at 12:39