【发布时间】:2011-08-04 17:51:20
【问题描述】:
我有一些具有以下结构的 JSON:
{"source":[
{"name":"john","age":20},
{"name":"michael","age":25},
{"name":"sara", "age":23}
]
}
我已将此 JSON 字符串命名为 mainJSON。我正在尝试使用以下 Java 代码访问元素“名称”和“年龄”:
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.
请指导我在哪里犯了错误以及如何纠正这个错误。
【问题讨论】:
-
你的源代码没有问题,我已经试过了。