I want to create a JSONObject object from the URL's content,
so I am getting the URL content from the google APIs, that's the result:
"results" : [
{
"address_components" : [
{
"long_name" : "29",
"short_name" : "29",
"types" : [ "street_number" ]
},
{
"long_name" : "Jean",
"short_name" : "Jean",
"types" : [ "route" ]
},
{
"long_name" : "Toulouse",
"short_name" : "Toulouse",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Haute-Garonne",
"short_name" : "31",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Midi",
"short_name" : "Midi",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "France",
"short_name" : "FR",
"types" : [ "country", "political" ]
},
{
"long_name" : "31000",
"short_name" : "31000",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "99 Jean , 31900 Toulouse, France",
"geometry" : {
"location" : {
"lat" : 43.6069496,
"lng" : 1.4498134
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 43.6082985802915,
"lng" : 1.451162380291502
},
"southwest" : {
"lat" : 43.6056006197085,
"lng" : 1.448464419708498
}
}
},
"place_id" : "ChIJTSvW45i8rhIRu8OEgnpnZMY",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
I would like to create a JSONObject from this content , something like
JSONObject obj = JSONObject.fromObject(urlConnection.getInputStream());
but checking the size of this object is 0
You need to read the content of that InputStream to a String, you can't use it directly that way.
Read the InputStream with something similar to this:
public static String slurp(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
And then use it to get a JSONObject:
JSONObject obj = JSONObject.fromObject(slurp(urlConnection.getInputStream()));
Done !
JSONParser parser = new JSONParser();
Object obj = parser.parse(new InputStreamReader(inputStream));
JSONObject jsonObject = (JSONObject) obj;
Related
Hoping there is an easy solution from someone on here. I know there are similar questions but I can't seem to modify them to work with my problem.
I am trying to parse the string for "formatted_address" in this json response:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Google Building 42",
"short_name" : "Google Bldg 42",
"types" : [ "premise" ]
},
{
"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" : "Google Bldg 42, 1600 Amphitheatre Pkwy, Mountain
View, CA 94043, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 37.42198310000001,
"lng" : -122.0853195
},
"southwest" : {
"lat" : 37.4214139,
"lng" : -122.0860042
}
},
"location" : {
"lat" : 37.4216548,
"lng" : -122.0856374
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4230474802915,
"lng" : -122.0843128697085
},
"southwest" : {
"lat" : 37.4203495197085,
"lng" : -122.0870108302915
}
}
},
"place_id" : "ChIJPzxqWQK6j4AR3OFRJ6LMaKo",
"types" : [ "premise" ]
}
],
"status" : "OK"
}
When previously using gson I was able to parse my result right away using:
Gson gson = new Gson();
JsonArray body = gson.fromJson(ResultString, JsonArray.class);
System.out.println(body.get(0).getAsJsonObject().get("elementnamehere").getAsString());
The main difference is that I can't put this result into JsonArray body. Instead (I believe since it has nested data) I have to make it a JsonObject, but I can not parse it for the life of me without getting Null. Any easy way to do this without making a POJO or Response Classes? If not can someone explain how/why to do that like so:
Parsing nested JSON data using GSON
You are almost there and you are correct that you need to parse JsonObject.
JsonObject body = gson.fromJson(json, JsonObject.class);
JsonArray results = body.get("results").getAsJsonArray();
JsonObject firstResult = results.get(0).getAsJsonObject();
JsonElement address = firstResult.get("formatted_address");
System.out.println(address.getAsString());
You can do it, but you do not have to use GSON necessarily.
You can parse a JSON as Java Objects with Jackson
. For example you can obtain: Object, List, Hashmap, Integer, String, etc. without POJO classes.
In android first add to gradle the following line:
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.0.1'
next import the mapper
import com.fasterxml.jackson.databind.ObjectMapper
at last you can use the mapper passing the String JSON value, example:
HashMap<*,*> object = new ObjectMapper().readValue(body, HashMap.class);
I hope it helps you. To see more about Jackson please visit: Jackson
first i have two arrays
ArrayList of type JSONObject jsonArrayResponse, jsonArraySubResponse
note: both arrays have the same size
here is my code to get and insert place data into an array :
for (int i = 0; i<jsonArrayResponse.size() - 1; i++) {
try {
JSONObject objectDictionary = jsonArrayResponse.get(i);
JSONObject objectSubDictionary = jsonArraySubResponse.get(i);
PlaceObject placeObject = new PlaceObject();
placeObject.setPlace_id(objectDictionary.getString("place_id"));
placeObject.setLat(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
placeObject.setLng(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
placeObject.setName(objectDictionary.getString("name"));
if (objectDictionary.has("photos")) {
JSONObject photoReferenceObject = objectDictionary.getJSONArray("photos").getJSONObject(0);
if (photoReferenceObject.has("photo_reference")) {
placeObject.setPhotoReference(photoReferenceObject.getString("photo_reference"));
}
}
if (objectSubDictionary.has("vicinity")) {
placeObject.setVicinity(objectSubDictionary.getString("vicinity"));
}
if (objectSubDictionary.has("formatted_address")) {
placeObject.setFormatted_address(objectSubDictionary.getString("formatted_address"));
}
if (objectSubDictionary.has("formatted_phone_number")) {
placeObject.setFormatted_phone_number(objectSubDictionary.getString("formatted_phone_number"));
}
if (objectSubDictionary.has("international_phone_number")) {
placeObject.setInternational_phone_number(objectSubDictionary.getString("international_phone_number"));
}
if (objectSubDictionary.has("url")) {
placeObject.setUrl(objectSubDictionary.getString("url"));
}
if (objectSubDictionary.has("website")) {
placeObject.setWebsite(objectSubDictionary.getString("website"));
}
if (objectSubDictionary.has("reviews")) {
ArrayList<Reviews> reviews = new ArrayList<Reviews>();
for (int j = 0; j<objectSubDictionary.getJSONArray("reviews").length(); j++) {
Reviews reviewObject = new Reviews();
JSONObject review = objectSubDictionary.getJSONArray("reviews").getJSONObject(j);
reviewObject.setAuthor_name(review.getString("author_name"));
if (review.has("rating")) {
reviewObject.setRating(review.getString("rating"));
}
reviewObject.setText(review.getString("text"));
if (review.has("type")) {
reviewObject.setType(review.getString("type"));
}
reviews.add(reviewObject);
}
placeObject.setReviews(reviews);
}
if (objectDictionary.has("opening_hours")) {
ArrayList<String> days = new ArrayList<String>();
for (int z = 0; z<objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").length(); z++) {
String day = objectDictionary.getJSONObject("opening_hours").getJSONArray("reviews").getString(z);
days.add(day);
}
placeObject.setWeekday_text(days);
}
if (objectDictionary.has("opening_hours")) {
if (objectDictionary.getJSONObject("opening_hours").has("open_now")) {
placeObject.setOpen_now(objectDictionary.getJSONObject("opening_hours").getBoolean("open_now"));
}
}
Float distanceInKilometers = distance(objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lat"), objectDictionary.getJSONObject("geometry").getJSONObject("location").getDouble("lng"), Global.loc.getLatitude(), Global.loc.getLongitude()) / 1000;
placeObject.setDistance(distanceInKilometers.doubleValue());
if (objectDictionary.has("rating")) {
placeObject.setRating(objectDictionary.getDouble("rating"));
}
if (objectDictionary.has("price_level")) {
placeObject.setPrice_level(objectDictionary.getInt("price_level"));
}
placeObjects.add(placeObject);
if (i == jsonArrayResponse.size() - 1) {
this.placeObjectsResopones = placeObjects;
this.placeObjects = placeObjects;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Sample Json data:
1) Places Search request:
{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870775,
"lng" : 151.199025
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png",
"id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
"name" : "Rhythmboat Cruises",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 270,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAF-LjFR1ZV93eawe1cU_3QNMCNmaGkowY7CnOf-kcNmPhNnPEG9W979jOuJJ1sGr75rhD5hqKzjD8vbMbSsRnq_Ni3ZIGfY6hKWmsOf3qHKJInkm4h55lzvLAXJVc-Rr4kI9O1tmIblblUpg2oqoq8RIQRMQJhFsTr5s9haxQ07EQHxoUO0ICubVFGYfJiMUPor1GnIWb5i8",
"width" : 519
}
],
"place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"reference" : "CoQBdQAAAFSiijw5-cAV68xdf2O18pKIZ0seJh03u9h9wk_lEdG-cP1dWvp_QGS4SNCBMk_fB06YRsfMrNkINtPez22p5lRIlj5ty_HmcNwcl6GZXbD2RdXsVfLYlQwnZQcnu7ihkjZp_2gk1-fWXql3GQ8-1BEGwgCxG-eaSnIJIBPuIpihEhAY1WYdxPvOWsPnb2-nGb6QGhTipN0lgaLpQTnkcMeAIEvCsSa0Ww",
"types" : [ "travel_agency", "restaurant", "food", "establishment" ],
"vicinity" : "Pyrmont Bay Wharf Darling Dr, Sydney"
},...
],
"status" : "OK"
}
2) Place Details request:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
},
{
"long_name" : "Pirrama Road",
"short_name" : "Pirrama Road",
"types" : [ "route" ]
},
{
"long_name" : "Pyrmont",
"short_name" : "Pyrmont",
"types" : [ "locality", "political" ]
},
{
"long_name" : "NSW",
"short_name" : "NSW",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "AU",
"short_name" : "AU",
"types" : [ "country", "political" ]
},
{
"long_name" : "2009",
"short_name" : "2009",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "48 Pirrama Road, Pyrmont NSW, Australia",
"formatted_phone_number" : "(02) 9374 4000",
"geometry" : {
"location" : {
"lat" : -33.8669710,
"lng" : 151.1958750
},
"viewport" : {
"northeast" : {
"lat" : -33.8665053,
"lng" : 151.1960371
},
"southwest" : {
"lat" : -33.8669293,
"lng" : 151.1952183
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
"international_phone_number" : "+61 2 9374 4000",
"name" : "Google Sydney",
"place_id" : "ChIJN1t_tDeuEmsRUsoyG83frY4",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"rating" : 4.70,
"reference" : "CnRsAAAA98C4wD-VFvzGq-KHVEFhlHuy1TD1W6UYZw7KjuvfVsKMRZkbCVBVDxXFOOCM108n9PuJMJxeAxix3WB6B16c1p2bY1ZQyOrcu1d9247xQhUmPgYjN37JMo5QBsWipTsnoIZA9yAzA-0pnxFM6yAcDhIQbU0z05f3xD3m9NQnhEDjvBoUw-BdcocVpXzKFcnMXUpf-nkyF1w",
"reviews" : [
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Simon Bengtsson",
"author_url" : "https://plus.google.com/104675092887960962573",
"language" : "en",
"rating" : 5,
"text" : "Just went inside to have a look at Google. Amazing.",
"time" : 1338440552869
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Felix Rauch Valenti",
"author_url" : "https://plus.google.com/103291556674373289857",
"language" : "en",
"rating" : 5,
"text" : "Best place to work :-)",
"time" : 1338411244325
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Chris",
"language" : "en",
"rating" : 5,
"text" : "Great place to work, always lots of free food!",
"time" : 1330467089039
}
],
"types" : [ "establishment" ],
"url" : "http://maps.google.com/maps/place?cid=10281119596374313554",
"vicinity" : "48 Pirrama Road, Pyrmont",
"website" : "http://www.google.com.au/"
},
"status" : "OK"
}
my problem is i get messing data and i think it skips if data took time to process. how to improve it to make sure i get all data of a place object ?
I note that
inside your loop this condition will not happen
if (i == jsonArrayResponse.size() - 1) {
...
}
because your loop will not continue till i == jsonArrayResponse.size() - 1
try to add = in the loop line like this
for (int i = 0; i <= jsonArrayResponse.size() - 1; i++) { ...}
Maybe this is the reason of missing last element from the array
Please provide sample data. I will try using GSON.
I am using the Search YELP API to develop a mobile application. I would like to display several businesses on a google map.
But unfortunately, I dont receive everything the coordinate object in my business.
"location":{
"neighborhoods":[
"West Ham",
"Stratford"
],
"state_code":"XGL",
"display_address":[
"409 High Street",
"West Ham",
"London E15 4QZ",
"UK"
],
"coordinate":{
"longitude":-2.16E-4,
"latitude":51.53907
},
"address":[
"409 High Street"
],
"postal_code":"E15 4QZ",
"geo_accuracy":5,
"country_code":"GB",
"city":"London"
},
How should I face with this problem ? Is there any walkaround to display my business on the map anyway ?
I just found an answer to my problem.
In case if the coordinates are not provided, I can use geocoding provided by
google map API
in formatting my request like this :
// Replace the API key below with a valid API key.
GeoApiContext context = new GeoApiContext().setApiKey("AIza...");
GeocodingResult[] results = GeocodingApi.geocode(context,
"1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);
which is similar to : https://maps.googleapis.com/maps/api/geocode/json?address=54+Frith+Street,+London,+GB
The API return me a JSON :
{
"results" : [
{
"address_components" : [
{
"long_name" : "54",
"short_name" : "54",
"types" : [ "street_number" ]
},
{
"long_name" : "Frith Street",
"short_name" : "Frith St",
"types" : [ "route" ]
},
{
"long_name" : "Soho",
"short_name" : "Soho",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Soho",
"short_name" : "Soho",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "London",
"short_name" : "London",
"types" : [ "locality", "political" ]
},
{
"long_name" : "London",
"short_name" : "London",
"types" : [ "postal_town" ]
},
{
"long_name" : "Greater London",
"short_name" : "Gt Lon",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "W1D 4SL",
"short_name" : "W1D 4SL",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "54 Frith Street, Soho, London W1D 4SL, UK",
"geometry" : {
"location" : {
"lat" : 51.5137474,
"lng" : -0.1318321
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 51.5150963802915,
"lng" : -0.130483119708498
},
"southwest" : {
"lat" : 51.5123984197085,
"lng" : -0.133181080291502
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Hope it will help other people in that case !
I'm trying to geocode an address and get the lat/lng coordinates in java. I'm able to geocode the address and have it return in a json object, but I'm unable to figure out how to use json-simple to parse the json below to get the lat/lng. Any help is appreciated.
{
"results" : [
{
"address_components" : [
{
"long_name" : "Minneapolis",
"short_name" : "Minneapolis",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Hennepin County",
"short_name" : "Hennepin County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Minnesota",
"short_name" : "MN",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Minneapolis, MN, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 45.05125,
"lng" : -93.193794
},
"southwest" : {
"lat" : 44.890144,
"lng" : -93.32916299999999
}
},
"location" : {
"lat" : 44.983334,
"lng" : -93.26666999999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 45.05125,
"lng" : -93.193794
},
"southwest" : {
"lat" : 44.890144,
"lng" : -93.32916299999999
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I've tried many different things, but this is my latest failure:
JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONObject results = (JSONObject) json.get("results"); <-- LINE 186
JSONArray geometry = (JSONArray) results.get("geometry");
for(int i = 0; i < geometry.size(); i++) {
JSONObject p = (JSONObject) geometry.get(i);
System.out.println(p);
}
It produces this stacktrace:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at com.AddressGeocoder.geocode(AddressGeocoder.java:186)
at com.AddressGeocoder.<init>(AddressGeocoder.java:48)
at com.Geocoder.main(Geocoder.java:7)
"results" is a JSONArray filled with (in this example just one) JSONObjects. These JSONObjects contain your expected JSONArray "geometry". Following is your code modified, so it loops through the results and printing the geometry data:
JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONArray results = (JSONArray) json.get("results");
for (int i = 0; i < results.size(); i++) {
// obtaining the i-th result
JSONObject result = (JSONObject) results.get(i);
JSONObject geometry = (JSONObject) result.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
System.out.println(location.get("lat"));
System.out.println(location.get("lng"));
}
That's because the "results" is a JSONArray. Try:
JSONArray results = (JSONArray ) json.getJSONArray("results");
So let me break it down for you so you can understand in JSON's {} denotes an object [] denotes an array. Simple? Yeah.
visual breakdown
results
index 0 ->
addressed_components(array)-->
long_name(single entity)
short_name(single entity)
types(array)
formatted_address(single entity)
geometry(huge ass object with nested objects)
types(array)
Basically, in the code you have right now results 0 index would contain "address_components", "formatted_address", "geometry", "types". (NOTE THIS IS ALL ONE OBJECT)
"Address_components" is a array.
Which contain multiple "Address_components."
"Geometry" is just a very very large object in which has many different attributes.
Lastly types is an array.
psuedo code to retrieve items from arrays, yo!
LOOP THROUGH JSON ARRAY
ASSIGN OBJECT VALUES // getting different objects that are indexed in the array.
(if you want to see code to see how all this is done let me know)
gl man.
I use net.sf.json library but you can use the logic
Here is the code :
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
public class Test {
static String str = "{ \"results\" : [ { \"address_components\" : [ { \"long_name\" : \"Minneapolis\", \"short_name\" : \"Minneapolis\", \"types\" : [ \"locality\", \"political\" ] }, { \"long_name\" : \"Hennepin County\", \"short_name\" : \"Hennepin County\", \"types\" : [ \"administrative_area_level_2\", \"political\" ] }, { \"long_name\" : \"Minnesota\", \"short_name\" : \"MN\", \"types\" : [ \"administrative_area_level_1\", \"political\" ] }, { \"long_name\" : \"United States\", \"short_name\" : \"US\", \"types\" : [ \"country\", \"political\" ] } ], \"formatted_address\" : \"Minneapolis, MN, USA\", \"geometry\" : { \"bounds\" : { \"northeast\" : { \"lat\" : 45.05125, \"lng\" : -93.193794 }, \"southwest\" : { \"lat\" : 44.890144, \"lng\" : -93.32916299999999 } }, \"location\" : { \"lat\" : 44.983334, \"lng\" : -93.26666999999999 }, \"location_type\" : \"APPROXIMATE\", \"viewport\" : { \"northeast\" : { \"lat\" : 45.05125, \"lng\" : -93.193794 }, \"southwest\" : { \"lat\" : 44.890144, \"lng\" : -93.32916299999999 } } }, \"types\" : [ \"locality\", \"political\" ] } ], \"status\" : \"OK\"}";
public static void main(String[] args) {
parseAndCheckJsonObj(str, "");
}
static void parseAndCheckJsonObj(Object str, Object key) {
/*
* Check whether str is Valid JSON
* String i.e. started by { [ or not
*/
if (JSONUtils.mayBeJSON(str.toString())) {
try {
if (JSONUtils.isArray(str)) {
/*if block Check for str as a Json Array*/
JSONArray rootArr = JSONArray.fromObject(str);
for (int i = 0; i < rootArr.size(); i++) {
parseAndCheckJsonObj(rootArr.get(i), key);
}
} else {
/*else block Check for str as a Json Object*/
JSONObject rootObj = JSONObject.fromObject(str);
Iterator keyIter = rootObj.keys();
while (keyIter.hasNext()) {
Object objKey = keyIter.next();
parseAndCheckJsonObj(rootObj.get(objKey), objKey);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (key.equals("lat"))
System.out.println("Latitude is : " + str);
else if (key.equals("lng"))
System.out.println("Longitude is : " + str);
else
System.out.println(key + " : " + str);
}
}
}
My Output is :
long_name : Minneapolis
short_name : Minneapolis
types : locality
types : political
long_name : Hennepin County
short_name : Hennepin County
types : administrative_area_level_2
types : political
long_name : Minnesota
short_name : MN
types : administrative_area_level_1
types : political
long_name : United States
short_name : US
types : country
types : political
formatted_address : Minneapolis, MN, USA
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
Latitude is : 44.983334
Longitude is : -93.26666999999999
location_type : APPROXIMATE
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
types : locality
types : political
status : OK
How retrieve "locality" from json google places api
in this json response:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "1623",
"short_name" : "1623",
"types" : [ "street_number" ]
},
{
"long_name" : "1/2 N Cahuenga Boulevard",
"short_name" : "1/2 N Cahuenga Boulevard",
"types" : [ "route" ]
},
{
"long_name" : "Los Angeles",
"short_name" : "Los Angeles",
"types" : [ "locality", "political" ]
},
{
"long_name" : "CA",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "US",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "90028",
"short_name" : "90028",
"types" : [ "postal_code" ]
}
i am using this code to get "lat" and "lng" :
JSONObject jsonLocation = c.getJSONObject("geometry").getJSONObject("location");
places_latitude = jsonLocation.getString("lat");
places_longitude = jsonLocation.getString("lng");
how do i get the "locality" value ? i'am using java.
Thank you,
Carlos.
I follow your way.
JSONArray address_components = c.getJSONObject("result").getJSONArray("address_components");
JSONObject obj = address_components.getJSONObject(2)
/*
obj is
{
"long_name" : "Los Angeles",
"short_name" : "Los Angeles",
"types" : [ "locality", "political" ]
}
*/
String your_result = obj.getJSONArray("types").get(0).toString();
The original json should be
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "1623",
"short_name" : "1623",
"types" : [ "street_number" ]
},
{
"long_name" : "1/2 N Cahuenga Boulevard",
"short_name" : "1/2 N Cahuenga Boulevard",
"types" : [ "route" ]
},
{
"long_name" : "Los Angeles",
"short_name" : "Los Angeles",
"types" : [ "locality", "political" ]
},
{
"long_name" : "CA",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "US",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "90028",
"short_name" : "90028",
"types" : [ "postal_code" ]
}
]
}
}