如何在Android中返回以下嵌套JSON Array的内容? [英] How do you return the contents of the following nested JSON Array in Android?

查看:92
本文介绍了如何在Android中返回以下嵌套JSON Array的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Hashmap或GSON进行W/O.这是我第一次解析嵌套数组.我知道如何解析单个数组和JSON对象.我已经看过这里的几个线程,并且我的代码基于此:

W/O using Hashmap or GSON. This is my first time parsing a nested array. I know how to parse a single array and JSON objects. I've looked at several threads on here and I'm basing my code on this one:

如何在android中解析此嵌套的JSON数组

我正在从以下URL解析以下JSON数据(从Postman粘贴).粘贴在下面的JSON结构.

I'm parsing the following JSON data(pasted from Postman) from the following url. JSON structure pasted below.

https://api.tfl .gov.uk/Line/victoria/Route/Sequence/inbound?serviceTypes =常规,夜晚

我想按顺序返回16个地铁站的列表;对于所有站,都返回"id":940GDCOELW或"naptanId:940DFDDKLJ09"和名称":"Warren Street Underground Station".它们存储在站"(非顺序)和"stopPointSequences"数组中,也存储在我开始解析"stopPointSequences",但是我不确定如何将数据添加到ArrayList.代码上方显示错误.或者,解析"orderedLineRoutes"会更容易吗?但是可以解析吗?通过将名称与ID匹配来确定它吗?我不确定数组中是否包含每个名称".下面粘贴了"stopPointSequence"数组的第一部分.谢谢您.

I want to return a list of 16 subway stations in sequential order; return "id":940GDCOELW" or "naptanId:940DFDDKLJ09" and "name":"Warren Street Underground Station" for all the stations. They are stored in both "stations"(non-sequential) and "stopPointSequences" arrays and also in "orderedLineRoutes". I started parsing "stopPointSequences", but I'm not sure how to add the data to the ArrayList. Error indicated above the code. Or, would it be easier to parse "orderedLineRoutes"? But is it possible to parse it by matching the name to the id? I'm not sure if every "name" is included in the array. The first part of "stopPointSequence" array pasted below. Thank you in advance.

    {
        "$type": "Tfl.Api.Presentation.Entities.RouteSequence, Tfl.Api.Presentation.Entities",
        "lineId": "victoria",
        "lineName": "Victoria",
        "direction": "inbound",
        "isOutboundOnly": false,
        "mode": "tube", 
        "lineStrings":[..];
         "stations":[..];
        "stopPointSequences":[
 {
            "$type": "Tfl.Api.Presentation.Entities.StopPointSequence, Tfl.Api.Presentation.Entities",
            "lineId": "victoria",
            "lineName": "Victoria",
            "direction": "inbound",
            "branchId": 0,
            "nextBranchIds": [],
            "prevBranchIds": [],
                "stopPoint": [
                    {
                        "$type": "Tfl.Api.Presentation.Entities.MatchedStop, Tfl.Api.Presentation.Entities",
                        "parentId": "HUBWHC",
                        "stationId": "940GZZLUWWL",
                        "icsId": "1000249",
                        "topMostParentId": "HUBWHC",
                        "modes": [
                            "tube"
                        ],
                        "stopType": "NaptanMetroStation",
                        "zone": "3",
                        "hasDisruption": true,
                         "lines": [{..}],
      "status": true,
                        "id": "940GZZLUWWL",
                        "name": "Walthamstow Central Underground Station",
                        "lat": 51.582965,
                        "lon": -0.019885
                    },
    ],
         "orderedLineRoutes": [
            {
                "$type": "Tfl.Api.Presentation.Entities.OrderedRoute, Tfl.Api.Presentation.Entities",
                "name": "Walthamstow Central  ↔  Brixton ",
                "naptanIds": [
                    "940GZZLUWWL",
                    "940GZZLUBLR",
                    "940GZZLUTMH",
                    "940GZZLUSVS",
                    "940GZZLUFPK",
                    "940GZZLUHAI",
                    "940GZZLUKSX",
                    "940GZZLUEUS",
                    "940GZZLUWRR",
                    "940GZZLUOXC",
                    "940GZZLUGPK",
                    "940GZZLUVIC",
                    "940GZZLUPCO",
                    "940GZZLUVXL",
                    "940GZZLUSKW",
                    "940GZZLUBXN"
                ],
                "serviceType": "Night"
            },
            {
                "$type": "Tfl.Api.Presentation.Entities.OrderedRoute, Tfl.Api.Presentation.Entities",
                "name": "Walthamstow Central  ↔  Brixton ",
                "naptanIds": [
                    "940GZZLUWWL",
                    "940GZZLUBLR",
                    "940GZZLUTMH",
                    "940GZZLUSVS",
                    "940GZZLUFPK",
                    "940GZZLUHAI",
                    "940GZZLUKSX",
                    "940GZZLUEUS",
                    "940GZZLUWRR",
                    "940GZZLUOXC",
                    "940GZZLUGPK",
                    "940GZZLUVIC",
                    "940GZZLUPCO",
                    "940GZZLUVXL",
                    "940GZZLUSKW",
                    "940GZZLUBXN"
                ],
                "serviceType": "Regular"          }]
    }},

JSONUTILS类:

JSONUTILS class:

     public static ArrayList<Stations> extractFeatureFromStationJson(String stationJSON) {
    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(stationJSON)) {
        return null;
    }
    ArrayList<Stations> stations = new ArrayList<>();
    try {
        // Create a JSONObject from the JSON response string
        JSONObject baseJsonResponse = new JSONObject(stationJSON);
        JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
        if (stopPointSequenceArrayList != null) {
            for (int i = 0; i < stopPointSequenceArrayList.length(); i++) {
                JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
                if (elem != null) {
                    JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
                    if (stopPointArrayList != null) {
                        for (int j = 0; j < stopPointArrayList.length(); j++) ;
                        JSONObject innerElem = stopPointArrayList.getJSONObject(i);
                        if (innerElem != null) {
                            String idStation = "";
                            if (innerElem.has("id")) {
                                idStation = innerElem.optString(KEY_STATION_ID);
                            }
                            String nameStation = "";
                            if (innerElem.has("name")) {
                                nameStation = innerElem.optString(KEY_STATION_NAME);
                            }
        //Error                    stopPointSequenceArrayList.add(stopPointArrayList);
                        }
                    }
                }
            }
        }
        //Error
        Stations station = new Stations(idStation, nameStation);
        stations.add(station);

    } catch (JSONException e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing stations JSON results", e);

    }
      // Return the list of stations
    return stations;

}           

推荐答案

您的代码中存在几个错误,因此现在应该可以使用.现在,您可以提取idname值:

There is couple errors inside your code so this should work now. You can now extract id and name values:

      try {
         ArrayList<Stations> stations = new ArrayList<>();

        // Create a JSONObject from the JSON response string
        JSONObject baseJsonResponse = new JSONObject(stationJSON);
        JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
        if (stopPointSequenceArrayList != null) {
            for (int i = 0; i < stopPointSequenceArrayList.length(); i++) {
                JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
                if (elem != null) {
                    JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
                    if (stopPointArrayList != null) {
                        for (int j = 0; j < stopPointArrayList.length(); j++) {
                            JSONObject innerElem = stopPointArrayList.getJSONObject(i);
                            if (innerElem != null) {
                                String id = innerElem.getString("id");
                                String name = innerElem.getString("name");
                                Log.d("Element", name);
                                Log.d("Element", id);
                                Stations station = new Stations(id, name);
                                stations.add(station);
                            }
                        }
                    }
                }
            }
         return stations;
        }
     return null; //something went wrong

    } catch (Exception e) {
        // If an error is thrown when executing any of the above statements in the "try" block,
        // catch the exception here, so the app doesn't crash. Print a log message
        // with the message from the exception.
        Log.e("QueryUtils", "Problem parsing stations JSON results", e);
        return null; // something went wrong exception is thrown

    }

这篇关于如何在Android中返回以下嵌套JSON Array的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆