Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

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

   }

}

2 Answers

0 votes
by (46k points)

Try this:

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      

    }

}

0 votes
ago by (1.7k points)

I'm using JSONObject class from a lib already included, and I don't mind changing to another one if I need it.

I know how to iterate over JSONArrays, but when I parse JSON data coming from Facebook, I get only JSONObject, not an array, and I would like to access that particular item at a certain index-JSONObject[0] for the first one. Which is impossible for me.

"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

}

End

JSONObject keys () method will return a JSONArray of the JSONObject keys, so we can just walk though it in loop in order to iterate over the elements:

JSONObject object = new JSONObject ();

JSONArray keys = object.names ();

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

String key = keys.getString (i);

String value = object.getString (key);

}

Related questions

0 votes
1 answer
0 votes
1 answer
+7 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...