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 :)
Related
I am trying to parse this file.
I am new to maps API so.
I am trying to parse this set into recyclerview
I trying to parse using String Request that works but I need json object to store data.
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "Ahmedabad",
"short_name" : "Ahmedabad",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Suradhara Society",
"short_name" : "Suradhara Society",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Khodiar Nagar",
"short_name" : "Khodiar Nagar",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Ahmedabad",
"short_name" : "Ahmedabad",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Gujarat",
"short_name" : "GJ",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "382350",
"short_name" : "382350",
"types" : [ "postal_code" ]
}
],
"adr_address" : "3rd Floor, Sardar Patel Mall, Nikol Gam Road, \u003cspan class=\"street-address\"\u003eBapunagar\u003c/span\u003e, \u003cspan class=\"extended-address\"\u003eSuradhara Society, Khodiar Nagar\u003c/span\u003e, \u003cspan class=\"locality\"\u003eAhmedabad\u003c/span\u003e, \u003cspan class=\"region\"\u003eGujarat\u003c/span\u003e \u003cspan class=\"postal-code\"\u003e382350\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eIndia\u003c/span\u003e",
"formatted_address" : "3rd Floor, Sardar Patel Mall, Nikol Gam Road, Bapunagar, Suradhara Society, Khodiar Nagar, Ahmedabad, Gujarat 382350, India",
"formatted_phone_number" : "085116 15040",
"geometry" : {
"location" : {
"lat" : 23.0379687,
"lng" : 72.6433222
},
"viewport" : {
"northeast" : {
"lat" : 23.0393176802915,
"lng" : 72.64467118029151
},
"southwest" : {
"lat" : 23.0366197197085,
"lng" : 72.64197321970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "7ddb8968d27481b07a700f6e34ac5442f528eaf2",
"international_phone_number" : "+91 85116 15040",
"name" : "Parsana Gym",
"photos" : [
{
"height" : 2322,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/104290859169763692879/photos\"\u003eAlpesh Patel\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAgWV9QS54sRCALTitzLBc7LowfL3gKMw_jbNaTSmeFM9GqqG6iu1hx4HJwj332LJQHpfk44xeAPIgYg0mexUJaoWd8mKIUt4oTUj0f-DvbmnrOG67Q5BwAh9eP6VjcPz3EhAHDkHpn52M8rURjiAncwzrGhTLyHQZ5qHXowonHaOnDvld63wrXg",
"width" : 4128
}
],
"place_id" : "ChIJEbpNLyCHXjkRny4b5TptHsY",
"plus_code" : {
"compound_code" : "2JQV+58 Ahmedabad, Gujarat, India",
"global_code" : "7JMJ2JQV+58"
},
"rating" : 4.4,
"reference" : "ChIJEbpNLyCHXjkRny4b5TptHsY",
"reviews" : [
{
"author_name" : "Sumit Patel",
"author_url" : "https://www.google.com/maps/contrib/101190972481759472779/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/-70hcgZha3k4/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbDZJQHYZ86bOPzJBQjG8VNA0_Sh6g/s128-c0x00000000-cc-rp-mo/photo.jpg",
"rating" : 5,
"relative_time_description" : "4 months ago",
"text" : "gym is good and trainer are also good.\nbut some new machine are require for excersize.",
"time" : 1527730807
},
{
"author_name" : "Mahesh Bhayani",
"author_url" : "https://www.google.com/maps/contrib/105571914899766322779/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/-EKevbjOaZsw/AAAAAAAAAAI/AAAAAAAAA4o/k75Wr5thZvg/s128-c0x00000000-cc-rp-mo/photo.jpg",
"rating" : 5,
"relative_time_description" : "4 months ago",
"text" : "Good atmosfiyar for parsana gym. Good service provide good trinar.",
"time" : 1527820640
},
{
"author_name" : "Nadiya Dipak",
"author_url" : "https://www.google.com/maps/contrib/100514831030336220877/reviews",
"language" : "en",
"profile_photo_url" : "https://lh6.googleusercontent.com/-he9oXwcUqLI/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbBq3ow6IHVx5QNQktTbXQEDI2v2xw/s128-c0x00000000-cc-rp-mo/photo.jpg",
"rating" : 5,
"relative_time_description" : "4 months ago",
"text" : "Parsana gym is very good sarvice provide . Nice team work",
"time" : 1527738686
}
],
"scope" : "GOOGLE",
"types" : [ "gym", "health", "point_of_interest", "establishment" ],
"url" : "https://maps.google.com/?cid=14275967968530345631",
"utc_offset" : 330,
"vicinity" : "3rd Floor, Sardar Patel Mall, Nikol Gam Road, Bapunagar, Ahmedabad"
},
"status" : "OK"
}
I use volley that gives parse exception.
Here is my code
I am trying to parse JSON format using volley using below code.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
JSONObject result = object.getJSONObject("result");
JSONArray array = result.getJSONArray("address_components");
Log.d("result", "" + array.length());
for (int adress = 0; adress < array.length(); adress++) {
JSONObject object1 = array.getJSONObject(i);
Log.d("result", object1.getString("long_name"));
Log.d("result", object1.getString("short_name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Error lisnter for request
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest );
Can Anyone help what I am missing in this?
here is exception.
Note-: org.json.JSONException: Value {"html_attributions":[],"result":{"address_components":[{"long_name":"Ahmedabad","short_name":"Ahmedabad","t.........}
Thanks in advance !!
Do this :
your response starts with jsonObject'{' not jsonArray'['
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("result");
JSONArray jsonArray = jsonObject.getJSONArray("address_components");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Log.d("result", object.getString("long_name"));
Log.d("result", object.getString("short_name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Error lisnter for request
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest );
I would like to get "lat" and "lng" from my JSON file and add to one array that keeps GeoPoint. I was trying to do it like that but it is not working for me :
protected List<GeoPoint> JsonArray(){
List<GeoPoint> endp = new ArrayList<GeoPoint>();
try{
JSONObject obj = new JSONObject(json);
JSONArray steps = obj.getJSONArray("routes");
for(int i=0;i<steps.length();i++){
JSONObject temp = steps.getJSONObject(i);
JSONObject ele = temp.optJSONObject("steps").optJSONObject("end_location");
ele.getJSONObject("lat");
ele.getJSONObject("lng");
double lat = Double.parseDouble(ele.getJSONObject("lat").toString());
double lng = Double.parseDouble(ele.getJSONObject("lng").toString());
endp.add(new GeoPoint((int)(lat *1E6),(int)(lng * 1E6)));
}
}catch (JSONException e) {
// TODO: handle exception
}
return endp;
}
Here's a part of how looks my JSON file:
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 41.87999000000001,
"lng" : -87.615020
},
"southwest" : {
"lat" : 29.74674000000001,
"lng" : -95.361220
}
},
"copyrights" : "Dane do Mapy ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "1 085 mil",
"value" : 1746457
},
"duration" : {
"text" : "16 godz. 39 min",
"value" : 59955
},
"end_address" : "1362 Chenevert Street, Houston, Teksas 77003, Stany Zjednoczone",
"end_location" : {
"lat" : 29.750110,
"lng" : -95.36016000000001
},
"start_address" : "138-230 South Columbus Drive, Chicago, Illinois 60601, Stany Zjednoczone",
"start_location" : {
"lat" : 41.87999000000001,
"lng" : -87.62075000000002
},
"steps" : [
{
"distance" : {
"text" : "338 stóp",
"value" : 103
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 41.88090,
"lng" : -87.62069000000001
},
"html_instructions" : "Kieruj się \u003cb\u003eS Columbus Dr\u003c/b\u003e na \u003cb\u003epółnoc\u003c/b\u003e w stronę \u003cb\u003eE Monroe St\u003c/b\u003e",
"polyline" : {
"points" : "}tr~FtlxuOuA#w##QMUA"
},
"start_location" : {
"lat" : 41.87999000000001,
"lng" : -87.62075000000002
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0,2 mil",
"value" : 266
},
"duration" : {
"text" : "1 min",
"value" : 33
},
"end_location" : {
"lat" : 41.88086000000001,
"lng" : -87.61750000000001
},
"html_instructions" : "Skręć \u003cb\u003ew prawo\u003c/b\u003e w \u003cb\u003eE Monroe St\u003c/b\u003e",
"polyline" : {
"points" : "szr~FhlxuO?SAyA?_B#yA?iBAaB?WBE#C#A?C?A#A?C?y#?_#"
},
"start_location" : {
"lat" : 41.88090,
"lng" : -87.62069000000001
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "2,0 mil",
"value" : 3186
},
"duration" : {
"text" : "3 min",
"value" : 180
},
"end_location" : {
"lat" : 41.85320,
"lng" : -87.61470000000001
},
"html_instructions" : "Skręć \u003cb\u003ew prawo\u003c/b\u003e w \u003cb\u003eU.S. 41 S\u003c/b\u003e",
"polyline" : {
"points" : "kzr~FjxwuOpMOZ#`PO|ACvDC#?lDCZAfMGjAA`#Av#?^?P?N#P#j#LRFNDRJRHZRb#\\b#^nAjA##JJXXb#b#z#v#RRp#`#RLr#Xn#Np#J`A#bBOp#Kv#K#?#?#A#?#?#?#?PEvBWxB]fDq#xA]jF_BTIj#QpGuBd#OBAf#SrDyAPGNG#AVKbA_#~#]|#]z#Y`F{AtCy#fHyB"
},
"start_location" : {
"lat" : 41.88086000000001,
"lng" : -87.61750000000001
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0,4 mil",
"value" : 581
},
"duration" : {
"text" : "1 min",
"value" : 30
},
"end_location" : {
"lat" : 41.848390,
"lng" : -87.614670
},
"html_instructions" : "Zjedź \u003cb\u003eInterstate 55 S\u003c/b\u003e w kierunku \u003cb\u003eSaint Louis\u003c/b\u003e",
"polyline" : {
"points" : "omm~FzfwuOVDPAN?VGlBk#b#M#?JEDAVI`A[dBi#`A[z#UPGZGf#E\\Ab##VDJBHBTFTHRJPNRNLL\\f#NXLTP\\BF"
},
"start_location" : {
"lat" : 41.85320,
"lng" : -87.61470000000001
},
"travel_mode" : "DRIVING"
},
Does anyone knows how can I do it in other way?
Your variable JSONArray steps = obj.getJSONArray("routes"); does not represent the "steps" part of the JSON object, but rather the "routes" part.
Also, you have skipped some of the levels in the JSON hierarchy. With the given JSON, you would need the following steps to traverse the JSON (I have omitted looping over the different arrays, except for the routes array)
JSONArray routes = obj.getJSONArray("routes");
for(int i=0; i < routes.length(); i++){
// Grab the first route
JSONObject route = routesArray.getJSONObject(i);
// Take all legs from the route
JSONArray legs = route.getJSONArray("legs");
// Grab first leg
JSONObject leg = legs.getJSONObject(0);
// Take all steps from the leg
JSONArray steps = leg.getJSONArray("steps");
// Grab first step
JSONObject step = steps.getJSONObject(0);
JSONObject endLocation = step.getJSONObject("end_location");
String lat = endLocation.getString("lat");
String lng = endLocation.getString("lng");
Reference: JSON parsing of Google Maps API in Android App
parse current json String as to get lat and lng :
JSONObject obj = new JSONObject(json);
JSONArray steps = obj.getJSONArray("routes");
for(int i=0;i<steps.length();i++){
JSONObject temp = steps.getJSONObject(i);
// get bounds JSONObject
JSONObject boundsjsonobj = temp.getJSONObject("bounds");
// get northeast JSONObject
JSONObject jsonboj_bounds_northeast= boundsjsonobj.getJSONObject("northeast");
// get northeast lng and lat
String str_northeast_lat=jsonboj_bounds_northeast.getString("lat");
String str_northeast_lng=jsonboj_bounds_northeast.getString("lng");
// get southwest JSONObject
JSONObject jsonboj_bounds_southwest= boundsjsonobj.getJSONObject("southwest");
// get northeast lng and lat
String str_southwest_lat=jsonboj_bounds_southwest.getString("lat");
String str_southwest_lng=jsonboj_bounds_southwest.getString("lng");
//get legs JsonArray from routes
JSONArray jsonarray_legs = temp.getJSONArray("legs");
for(int j=0;j<jsonarray_legs.length();j++){
JSONObject jobjlegs = jsonarray_legs.getJSONObject(j);
// get end_location json object
JSONObject jobjlegs_end_location = jobjlegs.getJSONObject("end_location");
String str_end_location_lat==jobjlegs_end_location.getString("lat");
String str_end_location_lng==jobjlegs_end_location.getString("lng");
// get start_address object
JSONObject jobjlegs_start_address = jobjlegs.getJSONObject("start_address");
String str_start_address_lat==jobjlegs_start_address.getString("lat");
String str_start_address_lng==jobjlegs_start_address.getString("lng");
// get steps jsonArray
JSONArray jsonarray_steps = jobjlegs.getJSONArray("steps");
for(int k=0;k<jsonarray_steps.length();k++){
JSONObject jobjsteps = jsonarray_steps.getJSONObject(k);
// get end_location jsonobject
JSONObject jobjsteps_end_location = jobjsteps.getJSONObject("end_location");
double latend = Double.parseDouble(jobjsteps_end_location.getString("lat"));
double lngend = Double.parseDouble(jobjsteps_end_location.getString("lng"));
endp.add(new GeoPoint((int)(latend *1E6),(int)(lngend * 1E6)));
// get start_location jsonobject
JSONObject jobjsteps_start_location = jobjsteps.getJSONObject("start_location");
double latstart = Double.parseDouble(jobjsteps_start_location.getString("lat"));
double lngstart = Double.parseDouble(jobjsteps_start_location.getString("lng"));
}
}
}
I am trying to parse some data from json file while using google api places i want to get the "names" only then save it in a list but i get json exception
here it's my file
{
"html_attributions" : [],
"next_page_token" : "ClRHAAAAyPJvpPTgNnOURBi9XhfVvw5J2Howz_h41h1HysWrYomdpQrRwMnWeKRKyiGU6ku6ZxxzQ3fLb598QgwyYYIF9PiK6ynAaBj-XOnbr7s2eTESEHTjEzwG8k6iwf3aFGTmeh0aFAH6KblOYgOw80zn7E-NgcdahjZl",
"results" : [
{
"geometry" : {
"location" : {
"lat" : 30.03735730,
"lng" : 31.2324840
},
"viewport" : {
"northeast" : {
"lat" : 30.04394240,
"lng" : 31.23577240
},
"southwest" : {
"lat" : 30.03077210,
"lng" : 31.22919559999999
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "b466d997e9c8b69f328895a42143f1da8b445e28",
"name" : "Garden City",
"reference" : "CqQBnAAAAHWLMK-4WmAwrZBlBfrSCs8ycrG7voN6sT-vFtqDUhVuxIVHJoAyA2JjVqzCSlJfJcI8DqUg1PFQUwQMDJvZinsx_-YJtYhr01Oa3wvj-CUvGR8m3WlxQEWUB0_tsm6mt5WDCEsMsnmhgRmgrOYmAMePGI_DndEBkOJjhqLoEo1VZblKaa730ZsBe1Wjp_NAYHm1reTeiHlBW5dMVhmCX7cSEAwbfJ3xpIJ_FUCoSlM-5hkaFM3vnuXUv1KVws2t-1L0CR8ldSRB",
"types" : [ "neighborhood", "political" ],
"vicinity" : "Cairo"
},
{
"geometry" : {
"location" : {
"lat" : 30.0429350,
"lng" : 31.2246040
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "710a28e1d1e2aefdd69ea6ec2e30fbfc9f5b54cb",
"name" : "Cairo Opera House",
"photos" : [
{
"height" : 478,
"html_attributions" : [ "From a Google User" ],
"photo_reference" : "CnRsAAAAJxKE7CfYmG89VEHODwClX4P3XbKD0h1j_xghhy0KvINsO9KMNWxkxq65xXPPXzZHWX104qjm3TTJaxh1mUeATTkRspBOVJll0JwZ-8fA_0DaXJ2RVr4pE7rPAKYkW9VE9qwIQ7ba_nvg5j7Nua96ihIQdEM9euo3M8jXH8CdpSj5ixoUq-W9Me_M9edgTscsjn5pBhnOTt8",
"width" : 613
}
],
"rating" : 4.50,
"reference" : "CoQBfAAAAD6AaWl7Ze1hxuelIZZkH8dD0VrsBBIpDOkfjwSItQ276DnGHiLYc4BEcPGyNuw_OPX7HfaPuIYFvN-ctpgcIV2tC5uw3nPP_Z4OTb5y0zD0CaelxZN3a-m0tBiqZHPylp7FpXOHERNc6BUInaWO3_h4Aze7M_FuOw21-zttSBvnEhBl62ERpUcU8nZIJy7DBrKuGhQn65AeXttY1axK8Qkvn7nKxDOuqA",
"types" : [ "establishment" ],
"vicinity" : "Opera Land, EL GEZIRAH"
},
{
"geometry" : {
"location" : {
"lat" : 30.0459720,
"lng" : 31.224110
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "fc80f712dc787d1c2c4382992e25895b8994bcdd",
"name" : "Cairo Tower",
"photos" : [
{
"height" : 1024,
"html_attributions" : [ "From a Google User" ],
"photo_reference" : "CnRoAAAAKUsL4sanCSNRjYRUSPbEbUoK73LuBWW36PuIAqebOTu3llxvJwtsQmtMpE_aqXjwtkZwjinZQqXWWd_8XQDGRtDPpKj5l97Jy02_zsT8KBLueOgaX4LlU0fAxKvQaM3SMJPehF2-x_qb0yn0Pbm4eRIQgX2VP1lXHnrefEKxk_NIshoUYZXYJAsB-z64TzWV4d6ACAxJqbo",
"width" : 768
}
],
i tried something like that
String data = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(data);
Object jj=jsonObj.getJSONObject("results").get("name");
but i got JSONEXCEPTION
results is an array not an object:
JSONObject jsonObj = new JSONObject(data);
JSONArray results =jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
Log.d("tag", "name: " + name)
}
Don't have a compiler here so cannot check syntax.
It was going good until I needed to parse the type of the place, the file is organized like this:
"geometry" : {
"location" : {
"lat" : 45.7849210,
"lng" : 11.8724490
},
"viewport" : {
"northeast" : {
"lat" : 45.81619110,
"lng" : 11.89575470
},
"southwest" : {
"lat" : 45.75432980,
"lng" : 11.84532520
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "a454072e2ba71d4e2331e39099261f086cd11d1e",
"name" : "Fonte",
"reference" : "CnRtAAAAUaGSsbXRv05lApqXueEKjOAjtkpEDz07ioe3vPS9HqpOIJSTTQWYObc6o6GfEq-pzVUtKT03oRWNx6ld-rUfdat47e8W3NbSsLY1NldO9iQEUjQOM9kIIOix8xLAvqh5YHUNTAela4Mo8HGSJPPBhhIQ9j4Uy_WrQtFO7qxirA0UHRoUsmY0ngstG5BBiHQNLkLgxTpsDEY",
"types" : [ "locality", "political" ],
"vicinity" : "Fonte"
},
As it is possible to notice that types is an string array I tried this approach:
JSONArray results = o.getJSONArray("results");
JSONObject tempObject = results.getJSONObject(0);
JSONArray typee = tempObject.getJSONArray("types");
String a = typee.getJSONObject(0).toString();
but it doesn't work.Any help will be appreciated.The whole JSON can be seen here: https://maps.googleapis.com/maps/api/place/search/json?location=45.7909,11.8700&radius=500&key=AIzaSyC9Ob9_u-2mxCHeItDHytDLmZP-P1QCejw&sensor=true.
JSONArray typee = tempObject.getJSONArray("types");
String a = typee.getString(0);
String b = typee.getString(1);
The above will return locality to variable a and political to variable b. Use typee.length() to find out how many elements are in the JSONArray if it's possible that types might have a variable number of elements.
I'm writing an android app that takes your current location and returns a list of the stores near you using the Google Places web service. I'm able to get back (what I think is) valid JSON, but when I go to parse the JSON using the Android JSONObject library, I get a parsing error.
Here is my class:
public class StoresNearMe {
private String result = "";
private String googleAPIKey = "Omitted for this example";
private String searchRadius = "50";
private Location myLocation;
final String TAG = getClass().getSimpleName();
public StoresNearMe(Location location){
myLocation = location;
}//StoresNearMe
public String getStoresNearMe(){
String result = "Nothing";
result = callGoogleWebService(buildURLForGooglePlaces(myLocation));
convertJSONtoArray(result);
return result;
}//getStoresNearMe
private String callGoogleWebService(String url){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
//request.addHeader("deviceId", deviceId);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
return result;
}//callWebService
private String buildURLForGooglePlaces(Location location){
String baseUrl = "https://maps.googleapis.com/maps/api/place/search/json?";
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
String url = baseUrl + "location=" + lat + "," + lon + "&" +
"radius=" + searchRadius + "&" + "sensor=false" +
"&" + "key=" + googleAPIKey;
Log.d(TAG,url);
return url;
}//buildURLForGooglePlaces
private void convertJSONtoArray(String rawJSON){
try {
JSONObject completeJSONObj = new JSONObject(rawJSON);
String json = completeJSONObj.toString();
Log.d(TAG,json);
JSONObject results = completeJSONObj.getJSONObject("results");
} catch (JSONException e) {
Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());
}
}//convertJSONtoArray
}//StoresNearMe
Here is the JSON returned by my call:
{
"html_attributions" : [
"Listings by \u003ca href=\"http://www.yellowpages.com.au/\"\u003eYellow Pages\u003c/a\u003e"
],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.86694910,
"lng" : 151.19549870
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "96760d4544ecdaaf2e87565915638238ca960f20",
"name" : "Pirrama Rd",
"reference" : "CnRqAAAAL0xKaK8vGlVlD-E5j-88K9YTuCKlOFfoBxhBUwMIBGxNQDC8UdkULJiiC0ICBRxpddCV09wyc-HtShEpquP-drX4sj4tI_tbfveDIbzfSAUaNQjYhhfjQ-eVi0VeWBXdXH0A8Z_-nKXKMo1fvCHtBhIQlAeLnFtotWnYonMUpU1DqxoUcI1weYioNnJPtnhXCThmx0W0ubU",
"types" : [ "route" ],
"vicinity" : "Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8669710,
"lng" : 151.1958750
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
"name" : "Google Sydney",
"reference" : "CnRkAAAAqvesgoigCyiZfDUwqjbravZHH5zsXrmskbQVhkFk1JMnnrnKNGQyoHBBYofTML_zZqaAUAKJeJCvReUn62oGzSgPgNSjWaXUVorKGDXAAjhGyeh2pRrJFwuC5qsgBYdyN4kY8kspJGu_bMo3xrranxIQ-mFIK_28TAqiagOAzY7RiBoUrZTvFJYSn0OXimLRRb_SQ3OKW44",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Road, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8670840,
"lng" : 151.195950
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "27e84d1acda19c14b9c7f5271242796891bc9c9e",
"name" : "Accenture",
"reference" : "CoQBfQAAAOpBriMi1e4itUquHQnv_jQyEOibrEnbWfAuJBJqBUzcTqNvY6luCcgiqHr3ensEO81bcTkt4fXGHFLxM7pERmxVvFnRnLsLy5xyQtVxIp8eQnYP6AZxLZyxbfGceG87r6A1lHCOQTFxK85HVFq7pYik9ud_ExxEtwHT3gO54pihEhDYEZ59AYpLMDmlRHk5__q_GhQdTS2wSOU2sAxy0j4J7EYwCuq6Iw",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Road, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8670520,
"lng" : 151.1957360
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "3ef986cd56bb3408bc1cf394f3dad9657c1d30f6",
"name" : "Doltone House - Darling Island Wharf",
"reference" : "CoQBewAAAExUq-YlS-bahqAJeJbfyGfkUrqyuKjZgCPxHznMZsHg1aHLWoFk8s_04DxDtEFAlSyRP-ZHNsceha6MB8JD7zFMjbYOKNJLSm9OcgFUOFB-4SZP3ZeRyYzna2032gayzUU1_8N-qtb_r2kfllGYAmgnaU7h6RC8haaf-dFfvdiiEhBUdWHpEeL7qwtB91BgNYdPGhTAjf0Xa7-MKHJRRCQu_g7XL80dzQ",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Road, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8671110,
"lng" : 151.1958750
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "258f23471a33cfa2828170660d94cd5797edb18c",
"name" : "Workplace6",
"reference" : "CnRhAAAAi_hm5c3gpntkNvC7NbQtIe5tcmosCIHHbzqhLURaH7mQ6inEOqg47_cltBrtFBEPSIqCuPQDC3UA-suLBfRslIwUNytKjC87Lt1ZrGXF6ZmnOR2rVcdCGdoWrdi977RHruBO21zbjzVWE-A3ZDn2NBIQ1Vu2-nr3E02DuJAtXL8x4BoUEBRWEHReK2LO3IoldvyyvSKb0Qs",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Rd, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8670520,
"lng" : 151.1957360
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "fe9136d6406ed2d35660dea37a0be34043c1a4f2",
"name" : "Doltone House",
"reference" : "CnRjAAAAo4zx1lM-veFEPBBeIRFETZoH8QRMmpHIBVtnmfOZ-Sh1-8p4vxKj-146pHGW6wPCZxIV0iIuAGow9OSsHubvY_kSnlBe5OB99ZSxHQsm0LrLh45c05Gf7C8jwp_9D7keDVDAC47MN65niSZW71fOrRIQxODppLktQZFWbf-V1N4gHxoUPetbj0zbU1kQj96YrRLzLKrbMoE",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Road, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.8666470,
"lng" : 151.195650
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "2722b46120160ec0a322e0a13cb0717ed41a696b",
"name" : "Biaggio",
"reference" : "CmRdAAAAp7wiB1b9cK-26FjhO2DVAGA-5uzuZxppHqCkR75dQxoMJiLD5G7H90_dKtNVDlRAdKSOx7hWlUoHGuwkbBA4ZhNIDrPdLWQ1a41sEN9gZJvU-t7uxoRzziZpTVSCU-AXEhDoQ36icc3OBaMH1xxnPgsEGhTB08nD6Q67ojrGYMJWrd4PojJKsw",
"types" : [ "establishment" ],
"vicinity" : "Pirrama Rd, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.86954560,
"lng" : 151.19454040
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "40840d476baa531e0227a353b1bef70262f66e7e",
"name" : "Pyrmont",
"reference" : "CnRnAAAA7aHZwg2JyjTI-xotS1q4XKgbg3eCUwOZm3Nz55Xf5Q2w-nZpBrrd2VAEl60On0puVl8bX7UaJTIECELr3KY2mL4s7zsIznItOiJEG-9QMlnreRSmxSBSUAkPghKWoq4OFbCr0dwNtZSKJFazcbCc1BIQSz5BZfCm-iyMZ8YOgvc4tBoU1CdnwsHS5PhB69jpYHsOvfWXEgo",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
Any help is appreciated - I'm not sure what is going wrong.
Thanks!
The problem is that you're trying to read an array in as an object.
Change
JSONObject results = completeJSONObj.getJSONObject("results");
to
JSONArray results = completeJSONObj.getJSONArray("results");
and the parse exception goes away.
your JSON should be Valid : example :
{\"key\":\"value\" }