gpt4 book ai didi

java - JSON 嵌套解析

转载 作者:行者123 更新时间:2023-12-01 20:07:01 25 4
gpt4 key购买 nike

谁能帮我设置这个 JSON 数据文件的解析。

我想了解每趟火车的出发情况。结构是出发 -> 全部 -> 0,1,2,3 等...谢谢

我试图获取某些字符串,例如时间、目的地和平台,然后将其显示在每次出发的列表中。

 private void jsonParse()
{
String url = key;

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("REST", response.toString());
try {
JSONArray jsonArray= response.getJSONArray("departures");
Log.d("REST", jsonArray.toString());

for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject departure = jsonArray.getJSONObject(i);
JSONObject all = departure.getJSONObject("all");

String Mode = all.getString("Mode");

TextViewResult.append(Mode + "\n");

}


} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});

Queue.add(request);
}

json file

最佳答案

如果我理解正确的话,你不会得到任何结果,对吗?

JSON 对象 (0, 1, ...) 是“all”的子对象,“all”是 JSONArray,而不是 JSONObject。而“departures”似乎是一个 JSONObject 而不是 JSONArray。你应该:

  • 将“departures”作为 JSONObject 排除在循环之外。

  • 从上一个中获取“all”作为 JSONArray,因为它是“departures”的子项,并且也在循环之外执行此操作 .

  • 迭代循环中的前一个 JSONArray,获取代表一个出发点的 JSONObject

因此,try 内的 block 将如下所示:

//logging omitted
JSONObject departuresJSONObj = response.getJSONObject("departures");
JSONArray allJSONArr = departuresJSONObj.getJSONArray("all");

JSONObject departureJSONObj;
String mode;

for (Object departureObj : allJSONArr) {

if (departureObj instanceof JSONObject) {

departureJSONObj = (JSONObject) departureObj;

mode = departureJSONObj.getString("mode"); //mode is lowercase in the JSON
TextViewResult.append(mode + "\n");

}

}

希望这有帮助。

关于java - JSON 嵌套解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983696/

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