简体   繁体   English

从Json Android获取多个对象

[英]Get multiple Objects from Json Android

I want to get data from this but its to confusing, how to do it. 我想从中获取数据,但令人困惑的是,如何做。 I want to access legs. 我要伸腿。 In legs distance then text. 双腿分开然后发短信。 Then after steps, in steps again distance and then text. 然后,在执行步骤之后,再次执行步骤,然后再输入距离。

In "routes" ==> "legs" --> distance --> text 在“路线” ==>“腿”->距离->文字

Then to get driving steps "routes" ==> "legs" ==> "steps" --> distance --> text 然后获得行驶步骤“路线” ==>“腿” ==>“步骤”->距离->文本

First there is object then array again object its too confusing. 首先是对象,然后是数组,再次对象太混乱了。 Any help would be appreciated. 任何帮助,将不胜感激。

{
       "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"
                      },

Manual method: 手动方式:

In few words Json gives you objects (beetwen { } ) or array (beetwen [ ] ). 简而言之,Json为您提供了对象(beetwen {})或数组(beetwen [])。 To get sth from deep in json you have to go through each level. 为了深入了解json,您必须遍历每个级别。 You put only fragment of json, but I closed it and we have at start json object (because main braces are {} ): 您只放入了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"
                  }]
            }
           ]
      }
     ]

} }

Let's say you have this as a String named "jsonString". 假设您有一个名为“ jsonString”的字符串。 You create json object like this: 您可以这样创建json对象:

JSONObject jsonObject = new JSONObject(jsonString);

Than you needs "routes" that is json array (between [] braces). 比您需要的是json数组的“路由”(在[]大括号之间)。 You create this array going deeper into your main jsonObject: 您创建此数组,并深入到您的主要jsonObject中:

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

To go through each array element (that are json objects) you iterate like this: 要遍历每个数组元素(即json对象),您需要像这样进行迭代:

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

And you get your "legs" like this: 这样,您的“腿”就会变得:

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

And deeper and deeper like above. 像上面那样越来越深。

Automatically 自动地

It's much easier to use Gson library and some Json Pojo parsers. 使用Gson库和一些Json Pojo解析器要容易得多。

You import gson in your build.gradle: 您在build.gradle中导入gson:

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

Than you can use this parser . 比您可以使用此解析器 Select source type "JSON" and "Annotation style" Gson. 选择源类型“ JSON”和“注释样式” Gson。 Put your json in text box and click Preview or download ZIP. 将您的json放在文本框中,然后单击“预览”或下载ZIP。 You can also put your package name and main class name or rename it manually later. 您还可以输入包名称和主类名称,或稍后手动重命名。 You will be given multiple model classes with top one called "Example" or your name. 您将获得多个模型类,其中一个顶级类称为“ Example”或您的名字。 It consists of two fields: 它包含两个字段:

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

Add all classes to your project and than you just parse your jsonString to your main class like this: 将所有类添加到项目中,然后像这样将JSONString解析到主类中:

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

And now you can access routes from this object. 现在,您可以从该对象访问路由。 And legs from routes and deeper and deeper... 越来越远的路线...

Please try below code to parse provided json keys value : 请尝试以下代码来解析提供的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());
    }

I think above code might be difficult for you to understand at this stage but once you understand then it will more helpful to you for future JSON parsing stuff. 我认为上面的代码在现阶段可能使您难以理解,但是一旦理解,它将对您将来的JSON解析工作有更大的帮助。

you can third parties(Gson, Logan Square,etc..) for parsing. 您可以通过第三方(Gson,Logan Square等)进行解析。 If you are trying to access it directly. 如果您尝试直接访问它。 Below you can find the sample code to access the "legs" array. 您可以在下面找到访问“ legs”数组的示例代码。

Let us assume 让我们假设

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

this "jsonObject" is the full json value, from which you want to access the "legs" array. 此“ jsonObject”是完整的json值,您想从该值访问“ legs”数组。 In this scenario the "legs" array is inside the "routes" array. 在这种情况下,“ legs”数组位于“ routes”数组内部。 So we need to get the "routes" array first and loop that array and get the "legs" array from each object and store in POJO class or if you want to fetch the "text" alone from the "distance" means you can store that in arraylist or string which you need. 因此,我们需要首先获取“ routes”数组,然后循环该数组,并从每个对象获取“ legs”数组,并将其存储在POJO类中;或者如果您想仅从“ distance”中获取“ text”,则可以存储您需要的arraylist或字符串中的内容。 Below is the sample code to get the text alone. 下面是仅获取文本的示例代码。

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

Hope this is helpful :) 希望这会有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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