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

107

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

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

This question is tagged with java android json

~ Asked on 2012-11-26 22:02:33

The Best Answer is


318

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!
    }
}

~ Answered on 2012-11-26 22:06:29


67

Short version of Franci's answer:

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

~ Answered on 2013-08-24 19:01:16


Most Viewed Questions: