简体   繁体   中英

JSON Nested Parsing

could anyone help me set up parsing for this JSON data file.

I want to get each train departure. The structure is departures -> all - > 0,1,2,3 etc... Thanks

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);
}

json文件

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 . And "departures" seems to be a JSONObject and not a JSONArray . You should:

  • Get "departures" as a JSONObject out of the loop.

  • Get "all" as a JSONArray from teh previous one, as it is a child of "departures", and do this also out of the loop .

  • Iterate over the previous JSONArray in the loop, obtaining the JSONObject 's which represent one departure each.

So, the block inside the try would look like this:

//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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM