gpt4 book ai didi

java - JSON获取没有对象的数组

转载 作者:行者123 更新时间:2023-11-29 20:11:14 25 4
gpt4 key购买 nike

我正在尝试解析 this JSON ,

{
"listname": "red",
"lists": [
{
"id": "01",
"name": "paw",
"list": [
{
"id": "A",
"name": "pawa",
"bar": "foo"
},
{
"id": "B",
"name": "pawb",
"bar": "foo"
}
]
},
{
"id": "02",
"name": "pew",
"list": [
{
"id": "A",
"name": "pewa",
"bar": "foo"
},
{
"id": "B",
"name": "pewb",
"bar": "foo"
}
]
},
{
"id": "03",
"name": "piw",
"list": [
{
"id": "A",
"name": "piwa",
"bar": "foo"
},
{
"id": "B",
"name": "piwb",
"bar": "foo"
}
]
}
]
}

我把它放在 Asset Folder 上,我读了它,它把它转换成 String 因为这里一切都很好,问题是当我试图得到lists 中的每个项目的 name 并尝试从 list 中获取所有名称 我试过这样做:

JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("lists"); //first get the lists
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}

JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("list"); //get the list
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}

但它没有显示任何内容……我错过了什么?

编辑

这就是我读取 JSON

的方式
 public static String loadJSONFromAsset(Context ctx, String str) {
String json = null;
try {

InputStream is = ctx.getAssets().open(str);

int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");

} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;

}

最佳答案

由于您的“列表”嵌套在 childJSONObject(来自“列表”)中,嵌套您的 for 循环以检索这组值(JSONobject)

JSONObject obj = new JSONObject(str);
//first get the top-level "lists"
JSONArray jsonMainArr = obj.getJSONArray("lists");
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//get the inner "list" from childJSONObject
JSONArray childJSONArray = childJSONObject.getJSONArray("list");
for (int j = 0; j < childJSONArray.length(); j++) {
JSONObject childJSONObjectB = childJSONArray.getJSONObject(j);
String name = childJSONObjectB.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
}

关于java - JSON获取没有对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860648/

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