Android: How do I get the following JSON Object? - java

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");

Related

I have a json string and I can't extract specific field

I Have a json String that looks like this:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Arad",
"short_name" : "Arad",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Arad",
"short_name" : "Arad",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Arad County",
"short_name" : "AR",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Romania",
"short_name" : "RO",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Arad, Romania",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 46.2217118,
"lng" : 21.3823449
},
"southwest" : {
"lat" : 46.1286902,
"lng" : 21.230371
}
},
"location" : {
"lat" : 46.1865606,
"lng" : 21.3122677
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 46.2217118,
"lng" : 21.3823449
},
"southwest" : {
"lat" : 46.1286902,
"lng" : 21.230371
}
}
},
"place_id" : "ChIJw1lco0uYRUcRkYRVPkoHcA8",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
My java code:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
JsonNode addressNode = resultsNode.path("address_components");
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
The last 2 line print 0.0 and 0.0. How can I obtain lat and lng information from this json?
p.s I diden't post the full url link.
Maybe the jsonNodes are not correct but I can't find the solution.
The problem is that results is not an object but an array of objects. You have to choose element by index. The proper solution is:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
JsonNode addressNode = resultsNode.get(0); //selecting first json object from an array
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
You may also want to iterate all objects in results, in that case code, which will print coordinates of each object, should be:
jsonString = readUrl("https://maps.googleapis.com/")
rootNode = objectMapper.readTree(jsonString);
JsonNode resultsNode = rootNode.path("results");
Iterator<JsonNode> results = resultsNode.elements();
while(results.hasNext()){
JsonNode addressNode = results.next();
JsonNode geometryNode = addressNode.path("geometry");
JsonNode locationNode = geometryNode.path("location");
JsonNode latNode = locationNode.path("lat");
JsonNode lngNode = locationNode.path("lng");
System.out.println(latNode.asDouble());
System.out.println(lngNode.asDouble());
}

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");
}

Java JSONObject get children

i want to create gmaps on my website.
I found, how to get coordinates.
{
"results" : [
{
// body
"formatted_address" : "PuĊ‚awska, Piaseczno, Polska",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
},
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
}
},
"partial_match" : true,
"types" : [ "route" ]
}
],
"status" : "OK"
}
I want to get:
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
From this Json.
I decided to user json-simple
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
My code is:
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
And i can get the first children: "results"
String json2 = json.get("results").toString();
json2 display correct body of "results"
But i cannot get "location" children.
How to do it ?
Thanks
I think you need to cast the call to json.get("results") to a JSONArray.
I.e.
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
JSONArray results = (JSONArray) json.get("results");
JSONObject resultObject = (JSONObject) results.get(0);
JSONObject location = (JSONObject) resultObject.get("location");
String lat = location.get("lat").toString();
String lng = location.get("lng").toString()
The trick is to look at what type the part of the json you're deserializing is and cast it to the appropriate type.
about this link
com.google.gson.JsonParser#parse(java.lang.String) is now deprecated
so use com.google.gson.JsonParser#parseString, it works pretty well
Kotlin Example:
val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject
Java Example:
JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

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"));

Android - How to parse JSONObject and JSONArrays

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.

Categories

Resources