解析 JSON 对象中的 JSON 数组 [英] Parsing JSON Array within JSON Object
问题描述
我有一些具有以下结构的 JSON:
I have some JSON with the following structure:
{"source":[
{"name":"john","age":20},
{"name":"michael","age":25},
{"name":"sara", "age":23}
]
}
我已将此 JSON 字符串命名为 mainJSON
.我正在尝试使用以下 Java 代码访问元素name"和age":
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");
}
我看到第 2 行的以下异常:
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.
推荐答案
mainJSON.getJSONArray("source")
返回一个 JSONArray
,因此您可以删除 新的JSONArray.
mainJSON.getJSONArray("source")
returns a JSONArray
, hence you can remove the new JSONArray.
带有对象参数的 JSONArray 构造函数期望它是一个集合或数组(不是 JSONArray)
The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)
试试这个:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
这篇关于解析 JSON 对象中的 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!