Parsing a JSON array in a JSON object

I have JSON with the following structure:

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

I named this JSON line as mainJSON . I am 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 am shown the following exception for line 2:

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

Tell me where I am making a mistake and how to fix it.

+45
java json parsing
Apr 13 2018-11-11T00:
source share
5 answers

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

A JSONArray contract with an object parameter expects it to be Collection or Array (not JSONArray)

Try the following:

 JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 
+48
Apr 13 2018-11-11T00:
source share

Your code is fine, just replace the following line:

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

with this line:

 JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 
+9
Jun 29 '13 at 17:21
source share

line 2 should be

 for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2** 

In line 3 I need to do

  JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString()); 
0
Dec 22 '15 at 18:29
source share
 private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } String jsonText = readAll(inputofyourjsonstream); JSONObject json = new JSONObject(jsonText); JSONArray arr = json.getJSONArray("sources"); 

Your arr will look like this: [{"Identifier": 1001, "Name": "Yon"}, {"Identifier": 1002, "Name": "Yon"}] You can use:

 arr.getJSONObject(index) 

to get the objects inside the array.

0
Apr 6 '16 at 19:43
source share

This might be the answer to your question:

 JSONArray msg1 = (JSONArray) json.get("source"); for(int i = 0; i < msg1.length(); i++){ String name = msg1.getString("name"); int age = msg1.getInt("age"); } 
-3
Jun 15 '15 at 6:47
source share



All Articles