{ "key1": "value1", "key2": "value2", "key3": "value3" }
How I can get each item's key and value without knowing the key nor value beforehand?
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.
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.
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.
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! } }
Short version of Franci's answer:
for(Iterator<String> iter = json.keys();iter.hasNext();) { String key = iter.next(); ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With