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

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

How can I get the key and value of each element without knowing in advance neither the key nor the value?

+92
java json android
Nov 26
source share
6 answers

Use the keys() iterator to repeat 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! } } 
+281
Nov 26
source share

Short answer Franky:

 for(Iterator<String> iter = json.keys();iter.hasNext();) { String key = iter.next(); ... } 
+63
Aug 24 '13 at 19:01
source share

You can use the keys() or names() method. keys() will provide you with an iterator containing all String property names in the object, while names() will provide you with an array of all key string names.

You can get the JSONObject documentation here

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

+3
Nov 26
source share

Franzi Penov The answer is correct. Many people did wrong without knowing the difference between JsonObject and JSONObject.

0
Dec 21 '18 at 8:58
source share

You will need to use Iterator to loop through the keys to get their values.

Here, in the Kotlin implementation, you will realize that the way I got the string uses optString() , which expects a String value or a nullable value.

 val keys = jsonObject.keys() while (keys.hasNext()) { val key = keys.next() val value = targetJson.optString(key) } 
0
Feb 04 '19 at 1:20
source share

Take a look at the JSONObject link:

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

Without actually using the object, it looks like using getNames () or keys (), which returns an Iterator path.

-one
Nov 26
source share



All Articles