Android - How to parse JSONObject and JSONArrays - java

My build is Android 2.2 Google API 8 , Im running from the emulator. I am trying try access Location long in this JSON Object. I get this after I use
InputStream instream = entity.getContent();
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
Google docs says it returns an array but with the surrounding curly braces It looks like an object.
I need to access lat and lon in the location field and store as doubles.
Ive searched but only seem to find help with simple files.
{
"results" : [
{
"address_components" : [
{
"long_name" : "20059",
"short_name" : "20059",
"types" : [ "postal_code" ]
},
{
"long_name" : "Washington D.C.",
"short_name" : "Washington D.C.",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Washington D.C., DC 20059, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 38.924920,
"lng" : -77.0178720
},
"southwest" : {
"lat" : 38.9189910,
"lng" : -77.02261200000001
}
},
"location" : {
"lat" : 38.92177780,
"lng" : -77.01974260
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 38.92510312068017,
"lng" : -77.01709437931984
},
"southwest" : {
"lat" : 38.91880787931983,
"lng" : -77.02338962068018
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}

JSONObject jObject = new JSONObject(convertStreamToString(instream));
JSONArray results = jObject.getJSONArray("result");
JSONObject geometry = results.getJSONObject(2);
JSONObject bounds = geometry.getJSONObject("bounds");
JSONObject northeast = geometry.getJSONObject("northeast");
double nLat = Double.parseDouble(northeast.getString("lat").toString());
double nLng = Double.parseDouble(northeast.getString("lng").toString());
That should give you lat/lng for northeast as doubles. Southeast is the same just replace northeast for southeast.

JSONObject location = myAwway.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
The 'results' JSONArray is probably the array Google docs suggested. They had just wrapped it up in a JSONObject with a status, so that you could check the status before attempting to work on the returned value.

Related

Open Google Maps with JSON response

I'm working on an android app with palces and routes. I have generated an url with origin, destination, waypoints optimizing the route with the API.
This is the code:
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origen +
"&destination=" + destination +
"&waypoints=optimize:true" + waypoints +
"&key=" + MAPS_API_KEY;
With this url I get a JSON response
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJg7rCFwEtQg0Rxe4x4GA7l1o",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJP2o6r25hLxMR_QZrIrfaJTc",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJg7rCFwEtQg0Rxe4x4GA7l1o",
"types" : [ "street_address" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 44.4292807,
"lng" : 12.6160845
},
"southwest" : {
"lat" : 40.519053,
"lng" : -3.6181872
}
},
"copyrights" : "Map data ©2022 Google, Inst. Geogr. Nacional",
"legs" : [
{
"distance" : {
"text" : "1.946 km",
"value" : 1946454
},
"duration" : {
I thought with this url Google Maps would be open automatically with the optimized route, but it is not like this. I'm trying to find out what I should do to open goolge maps with the route, but I don't find the solution.
Someone here have the solution? Thank you!!!

How can I get the longitude and latitude of a specific place using Google's GeoCoder Java Client?

I am trying to get the longitude and latitude of a specific address.
This is the result of the GeoCoded response with the address I am using as a parameter.
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"plus_code": {
"compound_code": "CWC8+W5 Mountain View, California, United States",
"global_code": "849VCWC8+W5"
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
I need to specifically get the longitude and latitude of the place.I am following the code here
I need the specific JSON field so that I can use it in my Java Code
I've found the solution.
The code in the github page shows that:
GeoApiContext context = new GeoApiContext.Builder().apiKey("AIza...").build();
GeocodingResult[] results = GeocodingApi.geocode(context,
"1600 Amphitheatre Parkway Mountain View, CA 94043").await();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(results[0].addressComponents));
The 4th line only accesses the "addressComponents" of the JSON String. To get the latitudes, I just had to use the corresponding field names and replace the 4th line of the code above with:
System.out.println(gson.toJson(results[0].geometry.location.lat));

Android: How do I get the following JSON Object?

I am trying to get the latitude and longitudes items from the location in a JSON but I am getting an array out of bounds exception on Android.
Here is the JSON file:
{
"results" : [
{
"address_components" : [
{
"long_name" : "21211",
"short_name" : "21211",
"types" : [ "postal_code" ]
},
{
"long_name" : "Baltimore",
"short_name" : "Balt",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Maryland",
"short_name" : "MD",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Baltimore, MD 21211, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
},
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 39.3476939,
"lng" : -76.619315
},
"southwest" : {
"lat" : 39.310951,
"lng" : -76.65690289999999
}
}
},
"place_id" : "ChIJn-Z5WtQEyIkRQx9CtdQF7-I",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
I just need the two attributes:
"location" : {
"lat" : 39.3289463,
"lng" : -76.63838319999999
}
I tried doing this but no luck:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
JSONObject geometry = results.getJSONObject(2); //ERROR RIGHT HERE!
JSONObject location = geometry.getJSONObject("location");
Double latitude = location.getDouble("lat");
Double longitude = location.getDouble("lng");
You should get JSONObject geometry = results.getJSONObject(0); because there is only one object in the array. However, if I were you, I'd create an ArrayList and use for(int i = 0; i < results.size(); i++) to get every object in case of coming more than one object, doing something like:
JSONObject jObj = new JSONObject(jData);
JSONArray results = jObj.getJSONArray("results");
ArrayList<LocationObject> _locationList = new ArrayList<>();
for(int i = 0; i < results.size(); i++){
JSONObject geometry = results.getJSONObject(i).getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
LocationObject _locationObject = new LocationObject();
_locationObject.setLat(location.getDouble("lat"));
_locationObject.setLng(location.getDouble("lng"));
_locationObject.add(_locationObject);
}
You cannot get your geomettry as you did,since there is no object at with the index 2 in your json object.
I think you have not formatted well your json responce.
Copy past your responce in this web site and you ll understand.
and here is some code:
JSONObject tmp = results.getJSONObject(0);
JSONObject geometery = tmp.getJSONObject ("geometery");

Gson - Getting value from JSON string

I have the following JSON string. I want to fetch formatted_address with the help of Gson library. I have done conversion of object to JSON. But this time want to get a value of a particular key and store it in a string.
{
"results" : [
{
"address_components" : [
{
"long_name" : "Mumbai Highway",
"short_name" : "NH 9",
"types" : [ "route" ]
},
{
"long_name" : "Kumar Swamy Nagar",
"short_name" : "Kumar Swamy Nagar",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Solapur",
"short_name" : "Solapur",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Solapur",
"short_name" : "Solapur",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Maharashtra",
"short_name" : "MH",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "413002",
"short_name" : "413002",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Mumbai Highway, Kumar Swamy Nagar, Solapur, Maharashtra 413002, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 17.6920319,
"lng" : 75.9232926
},
"southwest" : {
"lat" : 17.6910298,
"lng" : 75.9215124
}
},
"location" : {
"lat" : 17.6915905,
"lng" : 75.9224399
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 17.6928798302915,
"lng" : 75.92375148029151
},
"southwest" : {
"lat" : 17.6901818697085,
"lng" : 75.92105351970851
}
}
},
"place_id" : "ChIJhZADyJLaxTsRj9W-lIgGaRM",
"types" : [ "route" ]
}
],
"status" : "OK"
}
I want to parse the JSON string ang get value of "formatted_address".
//result is your json data in the form of string..convert json data to string.
JSONObject returnValue = new JSONObject(result);
//getting array from json
JSONArray results= returnValue.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject ParentObject = results.getJSONObject(i);
//getting particular_key...
String format_addrs=ParentObject.getString("formatted_address");
}

Parsing google geocode result in java - getting JSONArray[0] not found (It is there)

EDIT: I have another program, which uses direction service. It works. When I use that code in this geocode project, it throws the same error. (Eclipse, Java EE, Tomcat7)
for reference here's the request
http://maps.googleapis.com/maps/api/geocode/json?address=vancouver,bc&sensor=true
Here's there code
JSONObject obj = new JSONObject(s);
JSONObject res = obj.getJSONArray("results").getJSONObject(0);
String "s" is the return json. This works:
System.out.println(obj.getJSONArray("results");
Though as soon as I try getJSONObject(0) I get the error. I was working with the directions service prior to this and it sends a very similar result.. which was working for me. Any advice is much appreciated! This has eaten a couple hours of my night now so I thought I'd seek some help.
String lat = obj.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lat");
As you can see here:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
**"lat"** : 37.4223329,
**"lng"** : -122.0844192
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4236818802915,
"lng" : -122.0830702197085
},
"southwest" : {
"lat" : 37.4209839197085,
"lng" : -122.0857681802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
lat(Latitude) and lng(Longitude) are of type Double, hence the correct code (if you need latitude and longitude as Strings) is:
String latitude = Double.toString(jsonTree.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
String longitude = Double.toString(jsonTree.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng"));

Categories

Resources