在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
,因此你可以删除 new 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屋!