I have some JSON with the following structure:
{\"source\":[
{\"name\":\"john\",\"age\":20},
{\"name\":\"michael\",\"age\":25},
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());
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");
}
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");
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.