I have some JSON with the following structure:

{"source":[{"name":"john","age":20},{"name":"michael","age":25},
{"name":"sara","age":23}]}

I have named this JSON string as mainJSON. I'm trying to access the elements "name" and "age" with the following Java code:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
for (int i = 0; i < jsonMainArr.length(); i++) {  // **line 2**
     JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
     String name = childJSONObject.getString("name");
     int age     = childJSONObject.getInt("age");
}

I'm being shown the following exception for line number 2:

org.json.JSONException: JSONArray initial value should be a string or collection or array.

Please guide me as to where I'm making the mistake and how to rectify this.

share|improve this question

3 Answers

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 
share|improve this answer
Hey, it worked. thanks a lot. – Amitava Chakraborty Apr 13 '11 at 13:51

If you are still running on this problem : just copy/paste this tutorial that answer directly to your question !! ;)

Android JSON Objects parsing Tutorial

share|improve this answer

The JSON you have is an object, not an array. An object starts with { and ends with }. An array starts with [ and ends with ]. The JSONArray constructor you're using requires an array (i.e. a string that starts with [ and ends with ]).

I would advise you to use JSONObject instead of JSONArray to parse your string and iterate through it. Otherwise, to work with the code you currently have, you can change your JSON so it is just

[{"name":"john","age":20},{"name":"michael","age":25},{"name":"sara","age":23}]

Hope it helps!

share|improve this answer
Hi,Thanks for the reply. Do you mean to say I should make the following change - JSONObject tempJSON = new JSONObject(mainJSON.getJSONObject("depSchedule")); – Amitava Chakraborty Apr 13 '11 at 13:48
There is an array inside the object... – Aleadam Apr 13 '11 at 13:59
no array inside the object – TechEnd Aug 16 '12 at 6:17

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.