Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON Array within JSON Object

Tags:

java

json

parsing

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.

like image 286
Amitava Chakraborty Avatar asked Apr 13 '11 13:04

Amitava Chakraborty


People also ask

How do you access an array inside a JSON object?

You can access the array values by using the index number: x = myObj. rights[0]; Program output.

Can a JSON object contain an array?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

How do you represent an array of objects in JSON?

JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma. The [ (square bracket) represents JSON array.

Does JSON parse return an array?

When using the JSON. parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.


2 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");  
like image 121
Chandu Avatar answered Sep 23 '22 11:09

Chandu


Your code is fine, just replace the following line:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source")); 

with this line:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 
like image 31
Imran Muhammad Avatar answered Sep 23 '22 11:09

Imran Muhammad