android - 你如何在Android中返回以下嵌套JSON数组的内容?

标签 android arrays json parsing multidimensional-array

W/O 使用 Hashmap 或 GS​​ON。这是我第一次解析嵌套数组。我知道如何解析单个数组和 JSON 对象。我在这里查看了几个线程,我的代码基于这个线程:

How to parse this nested JSON array in android

我正在从以下 url 解析以下 JSON 数据(从 Postman 粘贴)。下面粘贴了 JSON 结构。

https://api.tfl.gov.uk/Line/victoria/Route/Sequence/inbound?serviceTypes=Regular,Night

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

    {
        "$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 类:

     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 值:

      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 - 你如何在Android中返回以下嵌套JSON数组的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090436/

相关文章:

android - 无法使用 Android Gradle 插件 3.0.1 解决 assembleAndroidTest 任务的依赖关系

Android List View Edit All View 外观

android - 如何使用 sqlite 作为字符串资源而不是 strings.xml 作为语言?

arrays - 在 VBA 中重新调光数组

javascript - 用 php 变量填充一个 javascript 数组

ruby-on-rails-3 - 如何_知道_在我的 Rails 3 应用程序中哪个 JSON 渲染器处于事件状态?

javascript - 数据库与 JavaScript 字符串连接

java - 编写自定义 Android ViewAction 以截取屏幕截图

javascript - JSON 解析错误 : Unterminated string

javascript - Angular - 如何根据数组中的值检查复选框?