解析 JSON 对象中的 JSON 数组
我有一些具有以下结构的JSON:
{"source":[
{"name":"john","age":20},
{"name":"michael","age":25},
{"name":"sara", "age":23}
]
}
我已将此 JSON 字符串命名为 .我正在尝试使用以下Java代码访问元素“name”和“age”:mainJSON
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");
}
我看到第 2 行的以下异常:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
请指导我在哪里犯了错误以及如何纠正这一点。