Can I get value from JSONObject without mention its name?
Asked Answered
I

3

6

My JSONObject:

{MyJSON:[{"id":"1","name":"panji","price":"100"}]}

I do this to get value of id:

menuitemArray.getJSONObject(i).getString("id");

Can I get the value of id, name or price, without mentioning its name, may be like index or another method?

Icelander answered 5/5, 2012 at 6:53 Comment(1)
What's wrong with mentioning the name? Are you facing issues with that?Cautious
V
10

You can call names() on a JSONObject to get a JSONArray of the names of its elements - this would let you do logic on them or retrieve their corresponding values dynamically.

Varletry answered 5/5, 2012 at 7:4 Comment(2)
Thanks for the answer. Never knew there is a names method for JSONObject and I has been wasting hours trying to use IteratorTracay
404 Not FoundArmet
H
2

You can get all the attributes of a JSONObject like this

for(Iteraor key=jsonObject.keys();itr.hasNext();) {
   jsonObject.get(key.next());
}
Herren answered 5/5, 2012 at 7:2 Comment(1)
I'm not sure that you can use an Iterator with the for-each syntax, as annoying as that is. AFAIK it only works with Iterables and arrays.Varletry
S
1
JSONObject obj = new JSONObject(json);
for(Iterator<String> keys=obj.keys();keys.hasNext();) {
    obj.get(keys.next());
}
Spector answered 13/1, 2016 at 16:14 Comment(1)
Can you please explain how it answers the question?Kym

© 2022 - 2024 — McMap. All rights reserved.