How to get data from arrays inside arrays

I am trying to extract html_instructions from this the problem is html_instructions is inside the "steps" array, which is inside the "legs" array, which is inside the "routes" array, how do I get "html_instructions"

Some part of Json:

{
  geocoded_waypoints: [],
  routes: [
    {
      bounds: {
        northeast: {
          lat: 39.4798194,
          lng: -8.529889899999999
        },
        southwest: {
          lat: 39.2591911,
          lng: -8.7332564
        }
      },
      copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
      legs: [
        {
          distance: {
            text: "44,6 km",
            value: 44551
          },
          duration: {
            text: "30 min.",
            value: 1818
          },
          end_address: "Torres Novas, Portugal",
          end_location: {
            lat: 39.47908200000001,
            lng: -8.5401204
          },
          start_address: "Santarém, Portugal",
          start_location: {
            lat: 39.2846595,
            lng: -8.7049071
          },
          steps: [
            {
              distance: {
              text: "0,3 km",
              value: 342
            },
          duration: {
            text: "1 min.",
            value: 60
          },
          end_location: {
            lat: 39.2822117,
            lng: -8.7036403
          },
          html_instructions: "Siga <b>sul</b> em direção a <b>N3</b>",
          polyline: {
            points: "cxwnFtdct@JEVGLCR?PDTFNHTNNNPJPDRDN?JCHCv@i@VQTK`CkF"
          },
          start_location: {
            lat: 39.2846595,
            lng: -8.7049071
          },
          travel_mode: "DRIVING"
        },
        {
          distance: {
            text: "0,6 km",
            value: 605
          },
          duration: {
            text: "1 min.",
            value: 66
          },
          end_location: {
            lat: 39.2772762,
          lng: -8.7058033
          },
          html_instructions: "Vire <b>à direita</b> em direção a <b>N3</b>",
          maneuver: "turn-right",
          polyline: {
            points: "yhwnFv|bt@NFx@XZL\RTNt@h@~C`CpAbAh@b@d@\h@^LJLHHBLDb@JP?JALAJAXCNCDANCLCLCPC`@Gz@KV@F@D@JDND"
          },
          start_location: {
            lat: 39.2822117,
            lng: -8.7036403
          },
        travel_mode: "DRIVING"
      },

      

This is what I have from java that doesn't work:

if (jsonStr != null) {
                try {
                    //JSONArray array = new JSONArray(jsonStr);
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    JSONArray routes = jsonObject.optJSONArray("routes");
                    if (routes != null) {
                        JSONArray legs = jsonObject.optJSONArray("legs");
                        if (legs != null){
                            JSONArray direcoes = jsonObject.optJSONArray("steps");
                            if (direcoes != null) {
                                for (int j = 0; j < direcoes.length(); j++) {
                                    JSONObject jsonObject1 = direcoes.getJSONObject(j);

                                    String Distancia = jsonObject1.getString("distance");
                                    String Duracao = jsonObject1.getString("duration");
                                    String Instrucoes = jsonObject1.getString("html_instructions");


                                    HashMap<String, String> direcao = new HashMap<>();

                                    direcao.put("distance", Distancia);
                                    direcao.put("duration", Duracao);
                                    direcao.put("html_instructions", Instrucoes);

                                    listaDirecoes.add(direcao);
                                }
                            }
                        }

                    }



                } catch (final JSONException e) {
                    Log.e(TAG, "ERROR: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }

      

-3


source to share


3 answers


Firstly, you are JSON not syntactically correct, but I assume this is due to the fact that you took a snippet from all data, but next time please either do it right or split the data for the minimum need to reproduce the case (i.e. It doesn't matter in "directions" or "duration." Next time you just remove it to get a sharper image.

This is what I have from java not working



It doesn't work because you are trying to read from jsonObject

most of the time, which is incorrect since it refers to the root of your hierarchy. In addition, having a variable named jsonObject

, jsonObject1

requesting the problem. The sooner the later you make a typo. So, to read what is in the field html_instructions

, you need to follow these steps (pseudocode):

// get the root object
JSONObject root = new JSONObject(jsonStr);

// get the routes (which is array)
JSONArray routes = jsonObject.optJSONArray("routes");

// get the 1st element of that array (which is object)
JSONObject singleRoute = routes.get(0);

// get route legs array
JSONArray legs = singleRoute.get("legs")

// get its first element
JSONObject singleLeg = legs.get(0);

// get html_instructions
String html = singleLeg.get("html_instructions");

      

0


source


This will return you the arraylist of the route ArrayList<LatLng> route

public abstract class DirectionsAsync extends AsyncTask<Void, Void, List<List<HashMap<String, String>>>> {
    private JSONObject jsonObject;

    public DirectionsAsync(JSONObject jResponse) {
        this.jsonObject = jResponse;
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(Void... voids) {
        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        try {
            JSONArray jRoutes = jsonObject.getJSONArray("routes");
            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                JSONArray jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();
                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {
                    JSONArray jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);
                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString(list.get(l).latitude));
                            hm.put("lng", Double.toString(list.get(l).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            List<HashMap<String, String>> path = result.get(i);
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
            }
        }
        onGetRoute(points);
    }

    private List<LatLng> decodePoly(String encoded) {
        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }
        return poly;
    }

    public abstract void onGetRoute(ArrayList<LatLng> route);
}

      



I think you need a drow route, so use the code below to execute the class

new DirectionsAsync(jResponse) {//pass here json response got by google
                            @Override
                            public void onGetRoute(ArrayList<LatLng> route) {
                                PolylineOptions polylineOptions = new PolylineOptions();
                                polylineOptions.width(10).color(Color.BLUE).addAll(route);
                                if (polyLine != null) polyLine.remove();
                                polyLine = mMap.addPolyline(polylineOptions);
                                polyLine.setPoints(route);
                            }
                        }.execute();

      

0


source


You'r JSON is wrong, but if it was just a typical mistake. use this.

JSONObject root = new JSONObject(jsonStr);
JSONArray routes = jsonObject.getJSONArray("routes");
if(routes!=bull && routes.lenght()>0);{
  JSONObject singleRoute = routes.get(0);
  JSONArray legs = singleRoute.get("legs")
  if(legs!=bull && legs.lenght()>0);{
     JSONObject singleLeg = legs.get(0);
     String html = singleLeg.get("html_instructions");
  }

      

}

0


source







All Articles