gpt4 book ai didi

java - JSONArray 解析错误

转载 作者:行者123 更新时间:2023-11-29 03:08:47 26 4
gpt4 key购买 nike

我需要解析 JSON 数组的帮助。

[
{
"Header1": [
{
"path": "upload/images/1430572021716.jpg"
},
{
"path": "upload/images/1430574003703.jpg"
}
]
},
{
"Header2": [
{
"path": "upload/images/1430574124119.jpg"
},
{
"path": "upload/images/1430574203001.jpg"
}
]
}
]

我收到了上面的 JSONArray。我想遍历数组并提取标题文本“Header1”和路径值

我一直遇到以下错误消息

at 0 of type org.json.jsonarray cannot be converted to jsonobject

经过一番研究,这是由于系统无法解析为 JSON 数组。如果我将“列表”数组更改为一个对象,它确实有效,但这不是一个数组,我失去了迭代它的能力。

这是我尝试解析数组的代码

    JSONArray mArray;

mArray = json;

//download json array
for (int i = 0; i < mArray.length(); i++) {
if(mArray != null) {
JSONArray list = mArray.getJSONArray(i);
if(list != null) {
for(int a = 0; a < list.length();a++) {
JSONObject elem = list.getJSONObject(a);
if (elem != null) {
listdata.add(elem.getString("path"));

}
}
}
}
}

最佳答案

您正试图将顶级数组的每个元素 视为另一个数组 - 不是,它是一个对象。然后该对象有另一个字段,其值 一个数组。所以你想要这样的东西:

for (int i = 0; i < json.length(); i++) {
JSONObject container = json.getJSONObject(i);
// We don't know the property name, but there's only one, apparently...
String key = container.keys().next();
JSONArray subarray = container.getJSONArray(key);
for (int j = 0; j < subarray.length(); j++) {
listdata.add(subarray.getJSONObject(j).getString("path"));
}
}

关于java - JSONArray 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30646675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com