Iterate over a JSONObject

+1 vote

JSON library called JSONObject is used(I don't mind switching if I need to)

We know how to iterate over JSONArrays, but when we parse JSON data from Facebook we 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, How can we do it?

{
   "http://http://url.com/": {
      "id": "http://http://url.com//"
   },
   "http://url2.co/": {
      "id": "http://url2.com//",
      "shares": 15
   }
   ,
   "http://url3.com/": {
      "id": "http://url3.com//",
      "shares": 15
   }
}
Jun 27, 2018 in Java by samarth295
• 2,220 points
128,685 views

12 answers to this question.

0 votes

There is no more simple and secure solution than using an iterator.

JSONObject names () method returns a JSONArray of the JSONObject keys, so you can simply walk though it in loop:

JSONObject objects = new JSONObject ();
JSONArray key = objects.names ();
for (int i = 0; i < key.length (); ++i) {
   String keys = key.getString (i); 
   String value = objects.getString (keys);
}
answered Jun 27, 2018 by scarlett
• 1,290 points
0 votes

to iterate over a json file you can use the following code:

jObj = new JSONObject(contents.trim());
Iterator<String> keys = jObj.keys();
while(keys.hasNext()) {
    String key = keys.next();
    if (jObject.get(key) instanceof JSONObject) {
    }
}
answered Dec 7, 2018 by Nitesh
0 votes
for(int i = 0; i<jobject.names().length(); i++){
    Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}

I used this to iterate over names

answered Dec 7, 2018 by Neha
0 votes
Iterator<JSONObject> itr = jsonObject.values().itr();
while (itr.hasNext()) {
 jsonChildObject = itr.next();
 // Do whatever you want with ChildObject 
  String id = (String) jsonChildObject.get("id");
}
answered Dec 7, 2018 by Kalgi
0 votes
JSONObject obj = new JSONObject ();
JSONArray key = object.names ();

for (int i = 0; i < key.length (); ++i) {

   String key = key.getString (i); // Here's your key
   String value = obj.getString (key); // Here's your value

}