我有一些具有以下结构的 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.
请指导我在哪里犯了错误以及如何纠正这个错误。
最佳答案
mainJSON.getJSONArray("source")
返回一个 JSONArray
,因此您可以删除 new JSONArray.
带有对象参数的 JSONArray 构造器期望它是一个集合或数组(不是 JSONArray)
试试这个:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
关于java - 在 JSON 对象中解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650171/