【发布时间】:2011-10-05 13:04:18
【问题描述】:
我有一个 JSON 文件,其中包含一些数组。我想遍历文件数组并获取它们的元素和值。
这是我的文件的样子:
{
"JObjects": {
"JArray1": [
{
"A": "a",
"B": "b",
"C": "c"
},
{
"A": "a1",
"B": "b2",
"C": "c3",
"D": "d4"
"E": "e5"
},
{
"A": "aa",
"B": "bb",
"C": "cc",
"D": "dd"
}
]
}
}
这是我已经走了多远:
JSONObject object = new JSONObject("json-file.json");
JSONObject getObject = object.getJSONObject("JObjects");
JSONArray getArray = getObject.getJSONArray("JArray1");
for(int i = 0; i < getArray.length(); i++)
{
JSONObject objects = getArray.getJSONArray(i);
//Iterate through the elements of the array i.
//Get thier value.
//Get the value for the first element and the value for the last element.
}
有可能做这样的事情吗?
我之所以要这样做是因为文件中的数组具有不同数量的元素。
【问题讨论】:
-
您使用的是 org.json API,还是其他 Java-to/from-JSON 库?
-
如果您使用的是
org.json.simple.JSONArray,那么访问JSONArray列表的第i个值是getArray.get(i)