简体   繁体   中英

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 [ ] ). To get sth from deep in json you have to go through each level. You put only fragment of json, but I closed it and we have at start json object (because main braces are {} ):

{
   "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". You create json object like this:

JSONObject jsonObject = new JSONObject(jsonString);

Than you needs "routes" that is json array (between [] braces). You create this array going deeper into your main jsonObject:

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

To go through each array element (that are json objects) you iterate like this:

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.

You import gson in your build.gradle:

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

Than you can use this parser . Select source type "JSON" and "Annotation style" Gson. Put your json in text box and click Preview or download 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. 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:

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 :

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.

you can third parties(Gson, Logan Square,etc..) for parsing. If you are trying to access it directly. Below you can find the sample code to access the "legs" array.

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. In this scenario the "legs" array is inside the "routes" array. 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. 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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