How to iterate over a JSONObject?

Eric Hjalmarsson picture Eric Hjalmarsson · Feb 5, 2012 · Viewed 586.9k times · Source

I use a JSON library called JSONObject (I don't mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSON data from Facebook I don't get an array, only a JSONObject, but I need to be able to access an item via its index, such as JSONObject[0] to get the first one, and I can't figure out how to do it.

{
   "http://http://url.com/": {
      "id": "http://http://url.com//"
   },
   "http://url2.co/": {
      "id": "http://url2.com//",
      "shares": 16
   }
   ,
   "http://url3.com/": {
      "id": "http://url3.com//",
      "shares": 16
   }
}

Answer

Rickey picture Rickey · May 15, 2012

Maybe this will help:

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}