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.
You can access the array values by using the index number: x = myObj. rights[0]; Program output.
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.
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.
When using the JSON. parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.
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");
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With