[java] Parsing JSON Array within JSON Object

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.

This question is related to java json parsing

The answer is


Your code is fine, just replace the following line:

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

with this line:

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

This could be an 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");
}

line 2 should be

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

For line 3, I'm having to do

    JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());

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 would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.


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"); 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?