[英]JSON Nested Parsing
谁能帮我为这个 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 对象 (0, 1, ...) 是“all”的子对象,它是JSONArray
,而不是JSONObject
。 “出发”似乎是JSONObject
而不是JSONArray
。 你应该:
将“出发”作为JSONObject
退出循环。
从前一个中获取“all”作为JSONArray
,因为它是“departures”的子项,并且在循环之外执行此操作。
遍历循环中的前一个JSONArray
,获得每个代表一个出发点的JSONObject
。
因此, try
中的块将如下所示:
//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");
}
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.