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?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
panji
  • 59
  • 1
  • 1
  • 5

3 Answers3

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
2

You can get all the attributes of a JSONObject like this

for(Iteraor key=jsonObject.keys();itr.hasNext();) {
   jsonObject.get(key.next());
}
gkamal
  • 20,777
  • 4
  • 60
  • 57
  • 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 `Iterable`s and arrays. – Paul Bellora May 05 '12 at 07:05
1
JSONObject obj = new JSONObject(json);
for(Iterator<String> keys=obj.keys();keys.hasNext();) {
    obj.get(keys.next());
}
Ziad Alzarka
  • 333
  • 1
  • 2
  • 12