[英]JSON Nested Parsing
could anyone help me set up parsing for this JSON data file.谁能帮我为这个 JSON 数据文件设置解析。
I want to get each train departure.我想得到每列火车的出发。 The structure is departures -> all - > 0,1,2,3 etc... Thanks结构是出发-> 全部-> 0,1,2,3 等...谢谢
I am trying to get certain strings such as time, destination and platform and then display it in a list for each departure.我正在尝试获取某些字符串,例如时间、目的地和平台,然后将其显示在每次出发的列表中。
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);
}
If I have understood correctly, you are getting no results, right?如果我理解正确,你不会得到任何结果,对吧?
The JSON objects (0, 1, ...) are children of "all", which is a JSONArray
, not a JSONObject
. JSON 对象 (0, 1, ...) 是“all”的子对象,它是JSONArray
,而不是JSONObject
。 And "departures" seems to be a JSONObject
and not a JSONArray
. “出发”似乎是JSONObject
而不是JSONArray
。 You should:你应该:
Get "departures" as a JSONObject
out of the loop.将“出发”作为JSONObject
退出循环。
Get "all" as a JSONArray
from teh previous one, as it is a child of "departures", and do this also out of the loop .从前一个中获取“all”作为JSONArray
,因为它是“departures”的子项,并且在循环之外执行此操作。
Iterate over the previous JSONArray
in the loop, obtaining the JSONObject
's which represent one departure each.遍历循环中的前一个JSONArray
,获得每个代表一个出发点的JSONObject
。
So, the block inside the try
would look like this:因此, 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");
}
}
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.