Save JSON values obtained from Google Directions

1

I need to get the data from a JSON obtained through the API of Google Directions .

I have this code, which apparently is correct:

List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
    JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
    Route route = new Route();

    JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
    JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
    JSONObject jsonLeg = jsonLegs.getJSONObject(0);
    JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
    JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
    JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
    JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
    JSONArray 

    jsonInstruction=jsonLeg.getJSONArray("html_instructions");
}

How can I save the values? I'll put a sample JSON so you can guide me:

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJNZzlDPLWYpYRCJBxIkFwiD0",
         "types" : [ "street_address" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJheKsagfQYpYRI6X_s8MFSO4",
         "types" : [ "route" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : -33.4907394,
               "lng" : -70.5542248
            },
            "southwest" : {
               "lat" : -33.592532,
               "lng" : -70.6199773
            }
         },
         "copyrights" : "Datos del mapa ©2017 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "13.9 km",
                  "value" : 13892
               },
               "duration" : {
                  "text" : "31 min",
                  "value" : 1842
               },
               "end_address" : "Alcalde Pedro Alarcón, San Joaquín, Región Metropolitana, Chile",
               "end_location" : {
                  "lat" : -33.4907394,
                  "lng" : -70.6199773
               },
               "start_address" : "Auriga 2044, Puente Alto, Región Metropolitana, Chile",
               "start_location" : {
                  "lat" : -33.592532,
                  "lng" : -70.5548994
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "80 m",
                        "value" : 80
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 9
                     },
                     "end_location" : {
                        "lat" : -33.5919623,
                        "lng" : -70.5543792
                     },
                     "html_instructions" : "Dirígete al \u003cb\u003enordeste\u003c/b\u003e por \u003cb\u003eAuriga\u003c/b\u003e hacia \u003cb\u003eAries\u003c/b\u003e.\u003cdiv style=\"font-size:0.9em\"\u003eCalle de uso restringido\u003c/div\u003e",
                     "polyline" : {
                        "points" : "h''lEbgsmLqBgB"
                     },
                     "start_location" : {
                        "lat" : -33.592532,
                        "lng" : -70.5548994
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "11 m",
                        "value" : 11
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 10
                     },
                     "end_location" : {
                        "lat" : -33.5918992,
                        "lng" : -70.5544702
                     },
                     "html_instructions" : "Gira a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eAries\u003c/b\u003e",
                     "maneuver" : "turn-left",
                     "polyline" : {
                        "points" : "v|_lEzcsmLKP"
                     },
                     "start_location" : {
                        "lat" : -33.5919623,
                        "lng" : -70.5543792
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "39 m",
                        "value" : 39
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 14
                     },
                     "end_location" : {
                        "lat" : -33.5916156,
                        "lng" : -70.5542248
                     },
                     "html_instructions" : "Gira a la \u003cb\u003ederecha\u003c/b\u003e con dirección a \u003cb\u003eCentral\u003c/b\u003e",
                     "maneuver" : "turn-right",
                     "polyline" : {
                        "points" : "j|_lEldsmLw@q@"
                     },
                     "start_location" : {
                        "lat" : -33.5918992,
                        "lng" : -70.5544702
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.3 km",
                        "value" : 344
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 51
                     },
                     "end_location" : {
                        "lat" : -33.589296,
                        "lng" : -70.5565952
                     },
                     "html_instructions" : "Gira a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eAv. Troncal San Francisco\u003c/b\u003e",
                     "maneuver" : "turn-left",
                     "polyline" : {
                        "points" : "rz_lEzbsmLIL}@|AGLKLQTKLYVUPy@d@iAl@k@Xg@t@mA'B"
                     },
                     "start_location" : {
                        "lat" : -33.5916156,
                        "lng" : -70.5542248
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "47 m",
                        "value" : 47
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 11
                     },
                     "end_location" : {
                        "lat" : -33.5888809,
                        "lng" : -70.5566925
                     },
                     "html_instructions" : "Continúa recto",
                     "maneuver" : "straight",
                     "polyline" : {
                        "points" : "bl_lEvqsmLsAP"
                     },
                     "start_location" : {
                        "lat" : -33.589296,
                        "lng" : -70.5565952
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "2.2 km",
                        "value" : 2236
                     },
                     "duration" : {
                        "text" : "6 min",
                        "value" : 330
                     },
                     "end_location" : {
                        "lat" : -33.5768974,
                        "lng" : -70.5755764
                     },
                     "html_instructions" : "Gira a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eAv. Troncal San Francisco\u003c/b\u003e",
                     "maneuver" : "turn-left",
                     "polyline" : {
                        "points" : "ni_lEhrsmL]r@[z@GZCHCFELINEHGFSRYTe@'@KJYZSXWf@MZGNGNGTGPCLCLU'B['Co@rFGd@EPELMXYn@eBfCU\UXSXcAzA{AtBaApAEFqAvAGDm@n@GFYZu@r@k@f@u@r@UXuAjCKR}@bBaBbDmCdFg@dAQ'@Yx@ITWz@Sb@q@dAm@x@k@v@k@x@g@p@q@bAILGHeCtDuBtCe@p@s@nA"
                     },
                     "start_location" : {
                        "lat" : -33.5888809,
                        "lng" : -70.5566925
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.8 km",
                        "value" : 835
                     },
                     "duration" : {
                        "text" : "2 min",
                        "value" : 124
                     },
                     "end_location" : {
                        "lat" : -33.5740375,
                        "lng" : -70.5826933
                     },
                     "html_instructions" : "Gira levemente a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eGabriela Ote\u003c/b\u003e",
                     "maneuver" : "turn-slight-left",
                     "polyline" : {
                        "points" : "r~|kEjhwmLUdAOt@O'@K'@EVAJ@L[hB]|AI'@Y|AYxAGZYzAWvAERGRGLGHQHQDQ@K@mABe@@A?O@WBQBKDQHUPQXEJGNAHCHAJAJAX?PHfATfCBZ@BFd@"
                     },
                     "start_location" : {
                        "lat" : -33.5768974,
                        "lng" : -70.5755764
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.7 km",
                        "value" : 698
                     },
                     "duration" : {
                        "text" : "2 min",
                        "value" : 101
                     },
                     "end_location" : {
                        "lat" : -33.5678508,
                        "lng" : -70.58396239999999
                     },
                     "html_instructions" : "Gira a la \u003cb\u003ederecha\u003c/b\u003e con dirección a \u003cb\u003eAv. Concha Y Toro\u003c/b\u003e",
                     "maneuver" : "turn-right",
                     "polyline" : {
                        "points" : "vl|kExtxmLgBRkC^m@HWDk@F]D_ALe@DUDYB]DsFn@oALa@FWBqAPKBaEf@"
                     },
                     "start_location" : {
                        "lat" : -33.5740375,
                        "lng" : -70.5826933
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "5.4 km",
                        "value" : 5433
                     },
                     "duration" : {
                        "text" : "10 min",
                        "value" : 603
                     },
                     "end_location" : {
                        "lat" : -33.5209376,
                        "lng" : -70.5990908
                     },
                     "html_instructions" : "Continúa por \u003cb\u003eAv. Vicuña Mackenna\u003c/b\u003e/\u003cb\u003eAv. Vicuña Mackenna Ote.\u003c/b\u003e",
                     "polyline" : {
                        "points" : "'f{kEv|xmLmALkBLeD\o@JwFh@kBHe@DOBaIz@SBw@De@DgBJ}@LM@mBVsANSBg@FmD'@aBPwAJeAHMBy@F_AHUB_BNgEl@oEZQBoBTUDsAJaBRuGp@k@FkBRwFb@mDXuD^WDUHKDa@N]Nq@XoBp@oAb@KBiDhAo@PoCx@KDi@R]LqEfBq@RgBn@sAd@iA^{C~@oXnJ{JhDcFfBuIxCk@Py@RoCv@yAb@cCt@SLmJtCKBOF}Bv@_Ct@mBx@a@NeA^oA^C@oAb@[Hs@Pa@Lk@R[H{@Vo@RWHIBQFKD]Ng@VUJKF"
                     },
                     "start_location" : {
                        "lat" : -33.5678508,
                        "lng" : -70.58396239999999
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "3.3 km",
                        "value" : 3317
                     },
                     "duration" : {
                        "text" : "7 min",
                        "value" : 401
                     },
                     "end_location" : {
                        "lat" : -33.4961257,
                        "lng" : -70.6164586
                     },
                     "html_instructions" : "Continúa recto por \u003cb\u003eAv. Vicuña Mackenna\u003c/b\u003e/\u003cb\u003eAv. Vicuña Mackenna Ote.\u003c/b\u003e",
                     "maneuver" : "straight",
                     "polyline" : {
                        "points" : "z'rkEh{{mLs@b@m@\a@TwE~Ck@'@sBrAk@^iAr@KFqBvA{@j@_BfA_@^SR_@b@i@p@QTcBpBgAxAKLqBlCY'@ORq@|@a@j@o@x@sAbBKLW\{@bAmDvEMPy@dAq@t@a@l@eArAg@n@[^mA~Ag@r@_BvBaAtA}@fA['@gDhFi@l@GFWVSLSJm@N{@Lw@L_@FoANsCb@UDeCb@MBI?wC'@iJjAQBQDYBmMxAUDM@cDj@eAPODyBb@yAR"
                     },
                     "start_location" : {
                        "lat" : -33.5209376,
                        "lng" : -70.5990908
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.2 km",
                        "value" : 167
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 47
                     },
                     "end_location" : {
                        "lat" : -33.4962922,
                        "lng" : -70.6180809
                     },
                     "html_instructions" : "Gira a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eAv. Salvador Allende\u003c/b\u003e",
                     "maneuver" : "turn-left",
                     "polyline" : {
                        "points" : "xemkEzg_nLK@O@D\Lp@f@nF"
                     },
                     "start_location" : {
                        "lat" : -33.4961257,
                        "lng" : -70.6164586
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.5 km",
                        "value" : 506
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 87
                     },
                     "end_location" : {
                        "lat" : -33.4918286,
                        "lng" : -70.61912989999999
                     },
                     "html_instructions" : "Gira a la \u003cb\u003ederecha\u003c/b\u003e con dirección a \u003cb\u003eSan Juan\u003c/b\u003e",
                     "maneuver" : "turn-right",
                     "polyline" : {
                        "points" : "xfmkE~q_nLe@FkC\gBVa@FM@mATUBkCb@MByCb@_BTy@L"
                     },
                     "start_location" : {
                        "lat" : -33.4962922,
                        "lng" : -70.6180809
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "59 m",
                        "value" : 59
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 12
                     },
                     "end_location" : {
                        "lat" : -33.491807,
                        "lng" : -70.6197696
                     },
                     "html_instructions" : "Gira a la \u003cb\u003eizquierda\u003c/b\u003e con dirección a \u003cb\u003eEl Pinar\u003c/b\u003e",
                     "maneuver" : "turn-left",
                     "polyline" : {
                        "points" : "|jlkEpx_nLCvA?f@"
                     },
                     "start_location" : {
                        "lat" : -33.4918286,
                        "lng" : -70.61912989999999
                     },
                     "travel_mode" : "DRIVING"
                  },
                  {
                     "distance" : {
                        "text" : "0.1 km",
                        "value" : 120
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 42
                     },
                     "end_location" : {
                        "lat" : -33.4907394,
                        "lng" : -70.6199773
                     },
                     "html_instructions" : "Gira a la \u003cb\u003ederecha\u003c/b\u003e con dirección a \u003cb\u003eAlcalde Pedro Alarcón\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eEl destino está a la derecha.\u003c/div\u003e",
                     "maneuver" : "turn-right",
                     "polyline" : {
                        "points" : "xjlkEp|_nLe@B_BRoAP"
                     },
                     "start_location" : {
                        "lat" : -33.491807,
                        "lng" : -70.6197696
                     },
                     "travel_mode" : "DRIVING"
                  }
               ],
               "traffic_speed_entry" : [],
               "via_waypoint" : []
            }
         ],
         "overview_polyline" : {
            "points" : "h''lEbgsmLqBgBKPw@q@ILeAjB]b@e@d@oAv@uBfAuBvCsAP]r@c@vAWn@MPm@h@q@l@m@t@e@bAO^WbAq@bFw@xGK^g@hAeDxE_DpEgAxAoCtCoAnAaBzAUXuAjCiAvBoFhKy@fBoAnDwDpFkBlC{FjIyA'Ce@zB[bAGb@@L[hBg@~Bs@vD_AbFO'@YRc@FyADoAF]Hg@ZWd@IXETCd@HxAXbDHh@sFr@oC\uC\cKjAwH'AyDZuEh@wFh@kBHu@HuI~@}AJgBJ}@L{BX}H|@mGj@oFd@gEl@oEZaCXaNvAwCZeL|@mEd@a@N_A^aDjAuHbC{C~@gA'@cGzB{DtAeF~Akd@xOyP'GeBd@iFzAcCt@SLyJxCmC~@_Ct@mBx@gBn@sA'@kBl@}C|@mCx@]LeAf@cCtAyKjHuBrA}B~A{CrBs@r@_E|E_FvGsCvDsDrE{DhFkBzBgB'CcAnAwG'JyAhBgDhFi@l@_@^g@Xm@N{@LwATcFr@{Ch@yOpBkOfBmGdAiCh@eBTO@D\Lp@f@nFqDd@iC^}F~@aIjAC~BeCVoAP"
         },
         "summary" : "Av. Vicuña Mackenna/Av. Vicuña Mackenna Ote.",
         "warnings" : [],
         "waypoint_order" : []
      }
   ],
   "status" : "OK"
}

To make everything clearer, I must obtain the travel distance, points of the trip, travel time and travel instructions. How to do it?

    
asked by zhet 12.05.2017 в 01:52
source

4 answers

2

You should simply review the structure so that you can correctly parse your .json file, as an example the file that you suggest in your question you can see here .

You should consider this

The answer .Json can be of two types:

  
  • If the .json starts with {it is considered as Json object.

  •   
  • If the .json starts with [it is considered as Json Arrangement

  •   

According to the structure of the .json file, your parser would be:

private void parseJson(String data){
    List<Route> routes = new ArrayList<Route>();
    JSONObject jsonData = null;
    try {
        jsonData = new JSONObject(data);
        JSONArray jsonRoutes = null;

        //Obtiene el JSONArray de routes.
        jsonRoutes = jsonData.getJSONArray("routes");
    for (int i = 0; i < jsonRoutes.length(); i++) {
        JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
        Route route = new Route();
        //Obtiene objeto overview_polyline.
        JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
        //Obtiene JSONArray legs.
        JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
        //Obtiene los objetos de array legs,
        for (int j = 0; j < jsonLegs.length(); j++) {

            JSONObject jsonLeg = jsonLegs.getJSONObject(j);
            //Obtiene el JSONObject de distance.
            JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
            //Obtiene el JSONArray de traffic_speed_entry.
            JSONArray jsonTrafficSpeedEntry = jsonLeg.getJSONArray("traffic_speed_entry");
            //Obtiene el valor de end_address.
            String jsonEndAddress = jsonLeg.getString("end_address");
            //Obtiene el JSONArray de via_waypoint.
            JSONArray jsonViaWayPoint = jsonLeg.getJSONArray("via_waypoint");
            //Obtiene el valor de start_address.
            String jsonStartAddress = jsonLeg.getString("start_address");
            //Obtiene el JSONObject de start_location.
            JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");

            //Obtiene el Array steps.
            JSONArray jsonSteps = jsonLeg.getJSONArray("steps");
            //Obtiene elementos de steps
            for (int k = 0; k < jsonSteps.length(); k++) {
                JSONObject jsonObjectInstruction = jsonSteps.getJSONObject(k);
                //Obtiene el valor de html_instructions
                String jsonInstruction = jsonObjectInstruction.optString("html_instructions");
                Log.i(TAG, "jsonInstruction: " + jsonInstruction);
                JSONObject jsonStepDistance = jsonObjectInstruction.getJSONObject("distance");
                Log.i(TAG, "jsonStepDistance: " + jsonStepDistance);
                String jsonTravelMode = jsonObjectInstruction.optString("travel_mode");
                Log.i(TAG, "jsonTravelMode: " + jsonTravelMode);
                String jsonManeuver = jsonObjectInstruction.optString("maneuver");
                Log.i(TAG, "jsonManeuver: " + jsonManeuver);
                JSONObject jsonStepStartLocation = jsonObjectInstruction.getJSONObject("start_location");
                Log.i(TAG, "jsonStepStartLocation: " + jsonStepStartLocation);
                JSONObject jsonStepPolyline = jsonObjectInstruction.getJSONObject("polyline");
                Log.i(TAG, "jsonStepPolyline: " + jsonStepPolyline);
                JSONObject jsonStepDuration = jsonObjectInstruction.getJSONObject("duration");
                Log.i(TAG, "jsonStepDuration: " + jsonStepDuration);
                JSONObject jsonEndLocation = jsonObjectInstruction.getJSONObject("end_location");
                Log.i(TAG, "jsonEndLocation: " + jsonEndLocation);
            }
            //Obtiene el objeto duration.
            JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
            //Obtiene el objeto end_location.
            JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");

            Log.i(TAG, "jsonDistance: "+ jsonDistance );
            Log.i(TAG, "jsonTrafficSpeedEntry: "+ jsonTrafficSpeedEntry );
            Log.i(TAG, "jsonEndAddress: "+ jsonEndAddress );
            Log.i(TAG, "jsonViaWayPoint: "+ jsonViaWayPoint );
            Log.i(TAG, "jsonStartAddress: "+ jsonStartAddress );
            Log.i(TAG, "jsonStartLocation: "+ jsonStartLocation );
            Log.i(TAG, "jsonDuration: " + jsonDuration);
            Log.i(TAG, "jsonEndLocation: " + jsonEndLocation);
        }

        Log.i(TAG, "TERMINA PARSER!");

    }

    } catch (JSONException e) {
        Log.e(TAG, "parseJson() " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "parseJson() " + e.getMessage());
    }

}

This is an example showing the navigation instructions:

You can download the example here , just define your url or use it to simulate your .json online:

link

As another option you can use GSON, check this article:

WORKING WITH JSON IN ANDROID (GSON)

    
answered by 17.05.2017 / 01:12
source
2

If you have the JSON as a String, an easy solution is to use Gson to pass that JSON to an object of your model. Imagine that I have a json with a car and I want to create a Car object with the data.

String jsonCar = "{name: 'Renault', cv: 300, doors_number: 3}";
Gson gson = new Gson();
Car car = gson.fromJSON(json, Car.class)
    
answered by 12.05.2017 в 14:21
1

As comrade @DavidLuque comments using the Gson library it is very easy to go through a structure json and extract the values

With the webtool jsonschema2pojo you can generate the objects Gson from a resource json .

Tutorial gson to understand more or less how it is used. and to go between substructures

...

    
answered by 15.05.2017 в 10:20
1

I've been reviewing your code and it seems to be correct except for the last line:

JSONArray jsonInstruction = jsonLeg.getJSONArray("html_instructions");

since according to the json you've put html_instructions it's inside each of the objects in the steps tag and not the label legs which is where you're trying to get the value.

So you should use the following code if you want to take all html_instructions :

//obtenemos el array de steps
JSONArray jsonSteps = jsonLeg.getJSONArray("steps");
    for (int i = 0; i < jsonSteps.length(); i++) {
         //obtenemos cada uno de los steps
         JSONObject jsonStep = jsonSteps .getJSONObject(i);

         //obtenemos los html_instructions
         JSONObject html_instructions = jsonStep .getJSONObject("html_instructions");

         //almacenamos o utilizamos los html_instruction
         ....
    }

On the other hand, if your intention was not to take the html_instructions and it was to take the steps , it would be enough to use the following:

JSONArray jsonSteps = jsonLeg.getJSONArray("steps");

I hope it will help you. Greetings.

    
answered by 15.05.2017 в 10:46