簡體   English   中英

你如何在Android中返回以下嵌套JSON數組的內容?

[英]How do you return the contents of the following nested JSON Array in Android?

不使用 Hashmap 或 GS​​ON。 這是我第一次解析嵌套數組。 我知道如何解析單個數組和 JSON 對象。 我已經看過這里的幾個線程,我的代碼基於這個:

如何在android中解析這個嵌套的JSON數組

我正在從以下 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"(non-sequential) 和 "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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM