I want to get longitude & latitude from a json. to do so i use the Google Maps API to get the json then i put it into a JsonElement but now i can't figure out how to read this values (latitude, longitude).
public static void getGeo(){
HttpResponse res = WS.url("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true").get();
int status = res.getStatus();
String type = res.getContentType();
JsonElement json = res.getJson();
JsonObject jsonObject = json.getAsJsonObject();
//with a system out i can see that the json is parsed correctly
System.out.print(jsonObject.get("results"));
}
the parsed json:
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"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": "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" ]
} ],
"geometry": {
"location": {
"lat": 37.4219720,
"lng": -122.0841430
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188244,
"lng": -122.0872906
},
"northeast": {
"lat": 37.4251196,
"lng": -122.0809954
}
}
}
} ]
}
any suggestion please ?
This should do the trick for you:
HttpResponse res = WS.url("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true").get();
JsonElement json = res.getJson();
System.out.println("JSON: " + json);
//with a system out i can see that the json is parsed correctly
JsonArray jsArr = json.getAsJsonObject().getAsJsonArray("results");
for (JsonElement jsEl : jsArr)
{
JsonObject locationObject = jsEl.getAsJsonObject().getAsJsonObject("geometry").getAsJsonObject("location");
double lat = locationObject.getAsJsonPrimitive("lat").getAsDouble();
double lng = locationObject.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("Lat is " + lat + " and lng is " + lng);
}
Related
What i would like to do is get all countries that have a region or subregion equal to "Southern Asia". Is there a function to perform compare both region and subregion to the string "Southern Asia"? I tried using filter but that didnt work out for me. The code below works fine to find regions that are equal to "Souther Asia"
Bson match = match(eq("region", "Southern Asia"));
This is an example of the json Data:
{
"_id": {
"$oid": "60c25ff18d787ab8bb976a6b"
},
"name": "Afghanistan",
"topLevelDomain": [
".af"
],
"alpha2Code": "AF",
"alpha3Code": "AFG",
"callingCodes": [
"93"
],
"capital": "Kabul",
"altSpellings": [
"AF",
"Afġānistān"
],
"region": "Asia",
"subregion": "Southern Asia",
"population": {
"$numberDouble": "27657145.0"
},
"latlng": [
{
"$numberDouble": "33.0"
},
{
"$numberDouble": "65.0"
}
],
"demonym": "Afghan",
"area": {
"$numberDouble": "652230.0"
},
"gini": {
"$numberDouble": "27.8"
},
"timezones": [
"UTC+04:30"
],
"borders": [
"IRN",
"PAK",
"TKM",
"UZB",
"TJK",
"CHN"
],
"nativeName": "افغانستان",
"numericCode": "004",
"currencies": [
{
"code": "AFN",
"name": "Afghan afghani",
"symbol": "؋"
}
],
"languages": [
{
"iso639_1": "ps",
"iso639_2": "pus",
"name": "Pashto",
"nativeName": "پښتو"
},
{
"iso639_1": "uz",
"iso639_2": "uzb",
"name": "Uzbek",
"nativeName": "Oʻzbek"
},
{
"iso639_1": "tk",
"iso639_2": "tuk",
"name": "Turkmen",
"nativeName": "Türkmen"
}
],
"translations": {
"de": "Afghanistan",
"es": "Afganistán",
"fr": "Afghanistan",
"ja": "アフガニスタン",
"it": "Afghanistan",
"br": "Afeganistão",
"pt": "Afeganistão",
"nl": "Afghanistan",
"hr": "Afganistan",
"fa": "افغانستان"
},
"flag": "https://restcountries.eu/data/afg.svg",
"regionalBlocs": [
{
"acronym": "SAARC",
"name": "South Asian Association for Regional Cooperation",
"otherAcronyms": [],
"otherNames": []
}
],
"cioc": "AFG"
}
Use the or filter like this:
Bson match = match(or(eq("region", "Southern Asia"), eq("subregion", "Southern Asia")));
The list below contains a collection of id's
List id_wanted = ['3894586', '2786438236', '895673985']
Given the list above, How do I remove elements from the JSON below that match with the id above List?
JSON:
{
"animals": [
{
"name": "lion",
"countries": [
{
"name": "kenya",
"facts": [
{
"features": [
"young male"
],
"age": "2y",
"id": "2837492"
}
]
},
{
"name": "tanzania",
"facts": [
{
"features": [
"cub"
],
"age": "0y",
"id": "3894586"
}
]
},
{
"name": "south africa",
"facts": [
{
"features": [
"adult lioness"
],
"age": "10y",
"id": "495684576"
},
{
"features": [
"young female"
],
"age": "4y",
"id": "2786438236"
}
]
}
]
},
{
"name": "giraffe",
"countries": [
{
"name": "zambia",
"facts": [
{
"features": [
"ex captivity"
],
"age": "20y",
"id": "343453509"
}
]
},
{
"name": "kenya",
"facts": [
{
"features": [
"male"
],
"age": "17y",
"id": "85604586"
}
]
},
{
"name": "uganda",
"facts": [
{
"features": [
"young female"
],
"age": "4y",
"id": "895673985"
},
{
"features": [
"none"
],
"age": "11y",
"id": "39860394758936764"
}
]
}
]
}
]
}
For example, the following block would be removed from the JSON above because id matches with the List id_wanted
{
"features": [
"young female"
],
"age": "4y",
"id": "2786438236"
}
Assuming your json is a String in a variable inputJson, it's probably easier to build a new Json document from the original with those values filtered out:
import groovy.json.*
def json = new JsonSlurper().parseText(inputJson)
List id_wanted = ['3894586', '2786438236', '895673985']
def result = new JsonBuilder([
animals: json.animals.collect {[
name: "$it.name",
countries: it.countries.collect { [
name: "$it.name",
facts: it.facts.findAll { !(it.id in id_wanted) }
]}
]}
]).toString()
You can parse your original json and modify the resulted data structure in-place using handy *. spread operator:
def json = slurper.parseText(original)
json.animals*.countries*.facts*.each { facts ->
facts.removeAll { fact -> fact.id in id_wanted }
}
def filtered = new JsonBuilder(json).toPrettyString()
println(filtered)
Output (with facts from id_wanted removed):
{
"animals": [
{
"name": "lion",
"countries": [
{
"name": "kenya",
"facts": [
{
"features": [
"young male"
],
"age": "2y",
"id": "2837492"
}
]
},
{
"name": "tanzania",
"facts": [
]
},
{
"name": "south africa",
"facts": [
{
"features": [
"adult lioness"
],
"age": "10y",
"id": "495684576"
}
]
}
]
},
{
"name": "giraffe",
"countries": [
{
"name": "zambia",
"facts": [
{
"features": [
"ex captivity"
],
"age": "20y",
"id": "343453509"
}
]
},
{
"name": "kenya",
"facts": [
{
"features": [
"male"
],
"age": "17y",
"id": "85604586"
}
]
},
{
"name": "uganda",
"facts": [
{
"features": [
"none"
],
"age": "11y",
"id": "39860394758936764"
}
]
}
]
}
]
}
What i am doing::I have a Json Structure I want to extract Bangalore having key adminArea5
{
"results": [
{
"locations": [
{
"latLng": {
"lng": 77.620949,
"lat": 12.931088
},
"adminArea4": "Bangalore Urban",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Bangalore",
"street": "Sarjapur Road",
"adminArea1": "IN",
"adminArea3": "Karnataka",
"type": "s",
"displayLatLng": {
"lng": 77.617502,
"lat": 12.928883
},
"linkId": 0,
"postalCode": "560095",
"sideOfStreet": "N",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur2d0821,8s=o5-9arwha&type=map&size=225,160&pois=purple-1,12.931088,77.620949,0,0|¢er=12.931088,77.620949&zoom=15&rand=981886032",
"adminArea3Type": "State"
}
],
"providedLocation": {
"latLng": {
"lng": 77.620949,
"lat": 12.931088
}
}
}
],
"options": {
"ignoreLatLngInput": false,
"maxResults": -1,
"thumbMaps": true
},
"info": {
"copyright": {
"text": "© 2014 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2014 MapQuest, Inc."
},
"statuscode": 0,
"messages": []
}
}
What i have done so far::
HttpGet httpget = new HttpGet(Const.URL_JSON_OBJECT);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
jsonobject = new JSONObject(Content);
Log.d("Content", Content.toString());
myString=jsonobject.getString("results").toString();
With the code above :: I have the JSON Structure
[
{
"providedLocation": {
"latLng": {
"lat": 12.931088,
"lng": 77.620949
}
},
"locations": [
{
"latLng": {
"lat": 12.931088,
"lng": 77.620949
},
"adminArea5Type": "City",
"adminArea4": "Bangalore Urban",
"adminArea5": "Bangalore",
"adminArea4Type": "County",
"street": "Sarjapur Road",
"adminArea1": "IN",
"adminArea3": "Karnataka",
"type": "s",
"displayLatLng": {
"lat": 12.928883,
"lng": 77.617502
},
"linkId": 0,
"postalCode": "560095",
"dragPoint": false,
"sideOfStreet": "N",
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"adminArea3Type": "State",
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur2d0821,8s=o5-9arwha&type=map&size=225,160&pois=purple-1,12.931088,77.620949,0,0|¢er=12.931088,77.620949&zoom=15&rand=-1939275403"
}
]
}
]
Question:: How to get Bangalore having key adminArea5
It looks like that you've an JSONArray() within your JSONObject.
Try to get the JSONOBject result, pick out the
JSONArray jsonArray = new JSONArray(jsonObject.get("results")).
In your JSONArray you can parse out your required data.
I am having an issue when trying to drill down further into json data to pull out specific key/value pairs. I am simply trying to pull the longtitude/latitude which I figured is a sub array of location which is a sub array of geometry.
My JSON:
results": [
{
"address_components": [
{
"long_name": "56",
"short_name": "56",
"types": [
"street_number"
]
},
{
"long_name": "Rosario Drive",
"short_name": "Rosario Dr",
"types": [
"route"
]
},
{
"long_name": "Waterbury",
"short_name": "Waterbury",
"types": [
"locality",
"political"
]
},
{
"long_name": "New Haven",
"short_name": "New Haven",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Connecticut",
"short_name": "CT",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "06708",
"short_name": "06708",
"types": [
"postal_code"
]
}
],
"formatted_address": "56 Rosario Drive, Waterbury, CT 06708, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 41.5291983,
"lng": -73.0523455
},
"southwest": {
"lat": 41.5291845,
"lng": -73.0523456
}
},
"location": {
"lat": 41.5291845,
"lng": -73.0523456
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 41.5305403802915,
"lng": -73.05099656970849
},
"southwest": {
"lat": 41.5278424197085,
"lng": -73.05369453029151
}
}
},
"types": [
"street_address"
]
},
{
"address_components": [
{
"long_name": "56",
"short_name": "56",
"types": [
"street_number"
]
},
{
"long_name": "Rosario Drive",
"short_name": "Rosario Dr",
"types": [
"route"
]
},
{
"long_name": "Woodbridge",
"short_name": "Woodbridge",
"types": [
"sublocality",
"political"
]
},
{
"long_name": "Vaughan",
"short_name": "Vaughan",
"types": [
"locality",
"political"
]
},
{
"long_name": "York Regional Municipality",
"short_name": "York Regional Municipality",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Ontario",
"short_name": "ON",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Canada",
"short_name": "CA",
"types": [
"country",
"political"
]
},
{
"long_name": "L4H",
"short_name": "L4H",
"types": [
"postal_code_prefix",
"postal_code"
]
}
],
"formatted_address": "56 Rosario Drive, Vaughan, ON L4H, Canada",
"geometry": {
"bounds": {
"northeast": {
"lat": 43.8324404,
"lng": -79.5703888
},
"southwest": {
"lat": 43.83244029999999,
"lng": -79.5704073
}
},
"location": {
"lat": 43.8324404,
"lng": -79.5704073
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 43.83378933029149,
"lng": -79.5690490697085
},
"southwest": {
"lat": 43.8310913697085,
"lng": -79.57174703029152
}
}
},
"types": [
"street_address"
]
},
{
"address_components": [
{
"long_name": "56",
"short_name": "56",
"types": [
"street_number"
]
},
{
"long_name": "Rosario Drive",
"short_name": "Rosario Dr",
"types": [
"route"
]
},
{
"long_name": "Summerville",
"short_name": "Summerville",
"types": [
"locality",
"political"
]
},
{
"long_name": "Dorchester",
"short_name": "Dorchester",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "South Carolina",
"short_name": "SC",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "29483",
"short_name": "29483",
"types": [
"postal_code"
]
}
],
"formatted_address": "56 Rosario Drive, Summerville, SC 29483, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 33.0303119,
"lng": -80.2500213
},
"southwest": {
"lat": 33.0302964,
"lng": -80.2500223
}
},
"location": {
"lat": 33.0302964,
"lng": -80.2500213
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 33.0316531302915,
"lng": -80.24867281970849
},
"southwest": {
"lat": 33.0289551697085,
"lng": -80.25137078029151
}
}
},
"partial_match": true,
"types": [
"street_address"
]
},
{
"address_components": [
{
"long_name": "56",
"short_name": "56",
"types": [
"street_number"
]
},
{
"long_name": "Rosario Drive",
"short_name": "Rosario Dr",
"types": [
"route"
]
},
{
"long_name": "Silver Lake",
"short_name": "Silver Lake",
"types": [
"neighborhood",
"political"
]
},
{
"long_name": "Providence",
"short_name": "Providence",
"types": [
"locality",
"political"
]
},
{
"long_name": "Providence",
"short_name": "Providence",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Rhode Island",
"short_name": "RI",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "02909",
"short_name": "02909",
"types": [
"postal_code"
]
}
],
"formatted_address": "56 Rosario Drive, Providence, RI 02909, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 41.8053438,
"lng": -71.4620833
},
"southwest": {
"lat": 41.8053382,
"lng": -71.4621001
}
},
"location": {
"lat": 41.8053382,
"lng": -71.4620833
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 41.8066899802915,
"lng": -71.46074271970849
},
"southwest": {
"lat": 41.8039920197085,
"lng": -71.46344068029151
}
}
},
"partial_match": true,
"types": [
"street_address"
]
}
],
"status": "OK"
}
My Code:
if (response != null)
{
JSONObject json;
try {
json = new JSONObject(response);
JSONObject results = json.getJSONObject("results");
JSONArray geometry = results.getJSONArray("geometry");
JSONArray location = geometry.getJSONArray("location");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Error:
On this line: JSONArray location = geometry.getJSONArray("location");
The method getJsonArray(int) in the type JSONArray is not applicable for the arguments String.
The structure of your JSON response object is:
"results" is JSONArray which contains 4 JSONObjects.
These JSONObjects contain other JSONObjects, such as
"address_components", "formatted_address", "geometry" and "types"
You want to get to JSONObjects "lat" and "lng" which are in JSOBObject "location", which in turn is in JSONObject "geometry".
The whole structure then is something like this:
JSONArray "results"
JSONObject [0]
JSONObject "address_components"
JSONObject "formatted_address"
JSONObject "geometry"
JSOBObject "location"
JSOBObject "lat" <------- you want this
JSOBObject "lng" <------- and this
JSONObject [1]
etc
To get to lat and lng, you could do:
JSONObject json;
try {
//create main JSONObject
json = new JSONObject(response);
//get results array
JSONArray results = json.getJSONArray("results");
//get first JSONObjects in the array
JSONObject firstObj = results.getJSONObject(0);
//get JSONObject for key "geometry"
JSONObject geometry = firstObj.getJSONObject("geometry");
//get JSONObject for key "location"
JSONObject location = geometry.getJSONObject("location");
//get strings for keys "lat" and "lng"
String lat = location.getString("lat");
String lng = location.getString("lng");
} catch (JSONException e) {
e.printStackTrace();
}
To get the remaining lat and lng, just go through all the objects in the array, so:
JSONObject firstObj = results.getJSONObject(1);
JSONObject firstObj = results.getJSONObject(2);
JSONObject firstObj = results.getJSONObject(3);
By the way, there's missing { and " at the beginning of your json response. I guess it's just an omission, but you can check if any JSON string is valid at jsonlint.com.
The value for the key geometry is no JSONArray but a JSONObject (notice the curly braces).
Thus, getJSONArray() does not work.
The error message is a bit misleading though.
The answer is in the error:
The method getJsonArray(int) in the type JSONArray is not applicable
for the arguments String.
It wants an index (int) but you are providing a Key (String).
Try locating the index of the parameter you're after and passing that in instead.
Or try this:
JSONObject geometry = results.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
I have a map like this :
{
facility-1={facility-kind1={param1=XPath-1, param2=XPath-2},
facility-kind2={param1=XPath-1, param2=XPath-2}
},
facility-2={facility-kind1={param1=XPath-1, param2=XPath-2},
facility-kind2={param1=XPath-1, param2=XPath-2}
}
}
I want to format it to JSON with the children under "children": [ .. ] tag:
[
{"title": "Item 1"},
{"title": "Folder 2",
"children": [
{"title": "Sub-item 2.1"},
{"title": "Sub-item 2.2"}
]
},
{"title": "Folder 3",
"children": [
{"title": "Sub-item 3.1"},
{"title": "Sub-item 3.2"}
]
}
]
When I use JSON I don't get the children tag :
{
"facility-1": {
"facility-kind1": {
"param1": "XPath-1",
"param2": "XPath-2"
},
"facility-kind2": {
"param1": "XPath-1",
"param2": "XPath-2"
}
},
"facility-2": {
"facility-kind1": {
"param1": "XPath-1",
"param2": "XPath-2"
},
"facility-kind2": {
"param1": "XPath-1",
"param2": "XPath-2"
}
}
}
Which is not what I want.
How can I get a JSON formatted the way I want?