Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

android

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

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

like image 938
user1763763 Avatar asked Nov 26 '12 22:11

user1763763


People also ask

How do I iterate through a key in JSON?

We can use Object. entries() to convert a JSON array to an iterable array of keys and values. Object. entries(obj) will return an iterable multidimensional array.

How do I know if JSONObject has key?

has() method – Class JsonObject. This is the convenience method that can be used to check of a property/member with the specified key is present in the JsonObject or not. This method returns true if the member with specified key exists, otherwise it returns false.

Can an object be a key in JSON?

JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon.


2 Answers

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!     } } 
like image 107
Franci Penov Avatar answered Oct 24 '22 13:10

Franci Penov


Short version of Franci's answer:

for(Iterator<String> iter = json.keys();iter.hasNext();) {     String key = iter.next();     ... } 
like image 41
Roozbeh Zabihollahi Avatar answered Oct 24 '22 13:10

Roozbeh Zabihollahi