簡體   English   中英

從Json Android獲取多個對象

[英]Get multiple Objects from Json Android

我想從中獲取數據,但令人困惑的是,如何做。 我要伸腿。 雙腿分開然后發短信。 然后,在執行步驟之后,再次執行步驟,然后再輸入距離。

在“路線” ==>“腿”->距離->文字

然后獲得行駛步驟“路線” ==>“腿” ==>“步驟”->距離->文本

首先是對象,然后是數組,再次對象太混亂了。 任何幫助,將不勝感激。

{
       "geocoded_waypoints" : [
          {
             "geocoder_status" : "OK",
             "place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
             "types" : [ "locality", "political" ]
          },
          {
             "geocoder_status" : "OK",
             "place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
             "types" : [ "locality", "political" ]
          }
       ],
       "routes" : [
          {
             "bounds" : {
                "northeast" : {
                   "lat" : 31.55462439999999,
                   "lng" : 74.3571711
                },
                "southwest" : {
                   "lat" : 30.1981178,
                   "lng" : 71.4687352
                }
             },
             "copyrights" : "Map data ©2016 Google",
             "legs" : [
                {
                   "distance" : {
                      "text" : "348 km",
                      "value" : 347978
                   },
                   "duration" : {
                      "text" : "4 hours 49 mins",
                      "value" : 17335
                   },
                   "end_address" : "Multan, Pakistan",
                   "end_location" : {
                      "lat" : 30.1981178,
                      "lng" : 71.4687352
                   },
                   "start_address" : "Lahore, Pakistan",
                   "start_location" : {
                      "lat" : 31.55462439999999,
                      "lng" : 74.3571711
                   },
                   "steps" : [
                      {
                         "distance" : {
                            "text" : "67 m",
                            "value" : 67
                         },
                         "duration" : {
                            "text" : "1 min",
                            "value" : 9
                         },
                         "end_location" : {
                            "lat" : 31.5549532,
                            "lng" : 74.3565735
                         },
                         "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
                         "polyline" : {
                            "points" : "k_r_Ei{ydM[r@e@bA"
                         },
                         "start_location" : {
                            "lat" : 31.55462439999999,
                            "lng" : 74.3571711
                         },
                         "travel_mode" : "DRIVING"
                      },

手動方式:

簡而言之,Json為您提供了對象(beetwen {})或數組(beetwen [])。 為了深入了解json,您必須遍歷每個級別。 您只放入了json的一部分,但我將其關閉,並且在開始時有json對象(因為主要括號為{}):

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
         "types" : [ "locality", "political" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
         "types" : [ "locality", "political" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 31.55462439999999,
               "lng" : 74.3571711
            },
            "southwest" : {
               "lat" : 30.1981178,
               "lng" : 71.4687352
            }
         },
         "copyrights" : "Map data ©2016 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "348 km",
                  "value" : 347978
               },
               "duration" : {
                  "text" : "4 hours 49 mins",
                  "value" : 17335
               },
               "end_address" : "Multan, Pakistan",
               "end_location" : {
                  "lat" : 30.1981178,
                  "lng" : 71.4687352
               },
               "start_address" : "Lahore, Pakistan",
               "start_location" : {
                  "lat" : 31.55462439999999,
                  "lng" : 74.3571711
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "67 m",
                        "value" : 67
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 9
                     },
                     "end_location" : {
                        "lat" : 31.5549532,
                        "lng" : 74.3565735
                     },
                     "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
                     "polyline" : {
                        "points" : "k_r_Ei{ydM[r@e@bA"
                     },
                     "start_location" : {
                        "lat" : 31.55462439999999,
                        "lng" : 74.3571711
                     },
                     "travel_mode" : "DRIVING"
                  }]
            }
           ]
      }
     ]

}

假設您有一個名為“ jsonString”的字符串。 您可以這樣創建json對象:

JSONObject jsonObject = new JSONObject(jsonString);

比您需要的是json數組的“路由”(在[]大括號之間)。 您創建此數組,並深入到您的主要jsonObject中:

JSONArray routesArray = jsonObject.getJSONArray("routes");

要遍歷每個數組元素(即json對象),您需要像這樣進行迭代:

for (int i = 0; i < routesArray.length(); i++) {
    //do sth
}

這樣,您的“腿”就會變得:

JSONObject routeObject = routesArray.get(i);
routeObject.get("legs");

像上面那樣越來越深。

自動地

使用Gson庫和一些Json Pojo解析器要容易得多。

您在build.gradle中導入gson:

compile 'com.google.code.gson:gson:2.4'

比您可以使用此解析器 選擇源類型“ JSON”和“注釋樣式” Gson。 將您的json放在文本框中,然后單擊“預覽”或下載ZIP。 您還可以輸入包名稱和主類名稱,或稍后手動重命名。 您將獲得多個模型類,其中一個頂級類稱為“ Example”或您的名字。 它包含兩個字段:

public class Example {
@SerializedName("geocoded_waypoints")
@Expose
private List<GeocodedWaypoint> geocodedWaypoints = new ArrayList<GeocodedWaypoint>();
@SerializedName("routes")
@Expose
private List<Route> routes = new ArrayList<Route>();

將所有類添加到項目中,然后像這樣將JSONString解析到主類中:

Example mainClassObject = new Gson().fromJson(jsonString, Example.class);

現在,您可以從該對象訪問路由。 越來越遠的路線...

請嘗試以下代碼來解析提供的json鍵值:

private void parseJson(String jsonString){
        ArrayList<String> legsDistanceList = new ArrayList<>();
        ArrayList<String> legStepsDistanceList = new ArrayList<>();
        try{
            JSONObject rootJson = new JSONObject(jsonString);
            if(rootJson.has("routes")) {
                JSONArray routesJsonArray = rootJson.getJSONArray("routes");
                for(int i=0;i<routesJsonArray.length();i++){
                    JSONObject routeJson = routesJsonArray.getJSONObject(i);
                    if(routeJson.has("legs")){
                        JSONArray legsJsonArray = routeJson.getJSONArray("legs");
                        for(int j=0;j<legsJsonArray.length();j++){
                            JSONObject legJson = legsJsonArray.getJSONObject(j);
                            if(legJson.has("distance")){
                                JSONObject distanceJson = legJson.getJSONObject("distance");
                                legsDistanceList.add(distanceJson.getString("text"));
                            }
                            if(legJson.has("steps")){
                                JSONArray stepsJsonArray = legJson.getJSONArray("steps");
                                for(int k=0;k<stepsJsonArray.length();k++){
                                    JSONObject stepJson = stepsJsonArray.getJSONObject(k);
                                    if(stepJson.has("distance")){
                                        JSONObject stepDistanceJson = stepJson.getJSONObject("distance");
                                        legStepsDistanceList.add(stepDistanceJson.getString("text"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Throwable e){
            e.printStackTrace();
        }

        Log.i("Legs Distance ",legsDistanceList.toString());
        Log.i("Legs Steps Distance ",legStepsDistanceList.toString());
    }

我認為上面的代碼在現階段可能使您難以理解,但是一旦理解,它將對您將來的JSON解析工作有更大的幫助。

您可以通過第三方(Gson,Logan Square等)進行解析。 如果您嘗試直接訪問它。 您可以在下面找到訪問“ legs”數組的示例代碼。

讓我們假設

JsonObject jsonObject =  new JsonObject("json string");

此“ jsonObject”是完整的json值,您想從該值訪問“ legs”數組。 在這種情況下,“ legs”數組位於“ routes”數組內部。 因此,我們需要首先獲取“ routes”數組,然后循環該數組,並從每個對象獲取“ legs”數組,並將其存儲在POJO類中;或者如果您想僅從“ distance”中獲取“ text”,則可以存儲您需要的arraylist或字符串中的內容。 下面是僅獲取文本的示例代碼。

JsonArray routesArray = jsonObject.optJsonArray("routes");
        if (routesArray != null) {
            for (int i = 0; i < routesArray.length(); i++) {
                JsonArray legsArray = routesArray.get(i).optJsonArray("legs");
                if (legsArray != null) {
                    for (int i = 0; i < legsArray.length(); i++) {
                        JsonObject legObject = legsArray.get(i);
                        JsonObject distanceObject = legObject.optJsonObject("distance");
                        String textValue = distanceObject.optString("text");
                    }
                }
            }
        }

希望這會有所幫助:)

暫無
暫無

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

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