jobin
jobin

Reputation: 1517

android json data retrieving

I am new to Json. I want to retrieve the distance between two places using json. I want to get "text"(Distance b/w two places) from "distance" object which is in "legs" array which in turn is in "routes" array. Link(http://maps.googleapis.com/maps/api/directions/json?origin=Adoor&destination=Thiruvananthapuram%20Zoo&sensor=false)

Java code:

 String uri="http://maps.googleapis.com/maps/api/directions/json?origin="+destination+"&destination="+tour_place+"&sensor=false";
            queue= Volley.newRequestQueue(getApplicationContext());
            JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.GET, uri, (String) null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                         JSONArray array=response.getJSONArray("legs");
                 distances.add(array.getJSONObject(0).getJSONObject("distance").getDouble("text"));


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error){

                }
            });
                queue.add(objectRequest);

Upvotes: 1

Views: 322

Answers (5)

malli
malli

Reputation: 640

From your response, you parse your routes array first.

JsonArray routes = response.getJsonArray("routes");

From here, you can get legs array like the following.

JsonArray legs = routes.getJsonArray("legs");

Upvotes: 0

Hari Krishnan
Hari Krishnan

Reputation: 6302

Try this

try{

JSONObject object = new JSONObject(thewholething.toString());
JSONArray routes =object.getJSONArray("routes");
JSONArray legs=routes.getJSONObject(0).getJSONArray("legs")
JSONObject distance =legs.getJSONObject(0).getJSONObject("distance");
String text=distance.getString("text");

}
 catch (JSONException e) {
        e.printStackTrace();
    }

Now the String text contains your value.

Upvotes: 0

Android Geek
Android Geek

Reputation: 9225

Try code below:

 try {
              StringRequest sr = new StringRequest(Request.Method.GET, uri, (String) null,  new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    pDialog.dismiss();
                    ;
                    Log.d("", ".......response====" + response.toString());

                    ////////
                    try {
                        JSONObject object = new JSONObject(response);
                        if (serverCode.equalsIgnoreCase("0")) {

                        }
                        if (serverCode.equalsIgnoreCase("1")) {
                            try {

                                if ("1".equals(serverCode))
                                {
                                    JSONArray jsonArray = object.getJSONArray("routes");
                                 if(jsonArray.length()>0)
                                 {
                                    for(int i=0; i<jsonArray.length(); i++)                                   
                                   {                                       
                                   JSONArray legs =jsonArray.getJSONArray("legs"); 
                                   if(legs.length()>0)
                                   {
                                    for(int i=0; i<legs.length(); i++)                                   
                                    {
                                    JSONObject object1 = legs.getJSONObject("distance");
                                    String distance = object1.getString("text");
                                   }
                               }
                           }
                       }
              }


                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
                    , new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pDialog.dismiss();
                    ;
                    //  VolleyLog.d("", "Error: " + error.getMessage());
                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        Toast.makeText(ForgotPasswordActivity.this, "Timeout Error",
                                Toast.LENGTH_LONG).show();
                    } else if (error instanceof AuthFailureError) {
                        VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                    } else if (error instanceof ServerError) {
                        VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                    } else if (error instanceof NetworkError) {
                        VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                    } else if (error instanceof ParseError) {
                        VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                    }
                }
            }
            ) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();

                    params.put("user_email", email);

                    return params;
                }
            };
            sr.setShouldCache(true);

            sr.setRetryPolicy(new DefaultRetryPolicy(50000 * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(sr);

        } catch (Exception e) {
            e.printStackTrace();
        }

Upvotes: 0

AL.
AL.

Reputation: 37768

Okay, will now post the code I did. Try this out.

try {
            JSONObject json = new JSONObject(jStr);
            JSONArray jaRoutes = json.getJSONArray("routes");
            JSONArray jaLegs = jaRoutes.getJSONObject(0).getJSONArray("legs");
            JSONObject joDistance = jaLegs.getJSONObject(0).getJSONObject("distance");
            String text = joDistance.getString("text");
            Toast.makeText(this, text, Toast.LENGTH_SHORT);
        } catch (JSONException e) {
            Log.d("SAMPLE", e.toString());
        }

Let me know if it works.

Upvotes: 1

Prokash Sarkar
Prokash Sarkar

Reputation: 11873

Try this,

List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");

                List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    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<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                }
                routes.add(path);
            }
        } catch (JSONException e) {
           e.printStackTrace();
        }catch (Exception e){
        }

Upvotes: 0

Related Questions