I receive JSON file from Google API Geocoding.Refer to JSON file here.Is there any other easy way to extract the data from this JSON in Apex?I want to retrieve a state value and result status code value.
This is my code based on @Bachovski and @eyescream post.I hope one day we can get direct field from Google API JSON instead of extract it like this.But for this time being,this one works for me.
public class Address{
public void updateAddressByGeocode(String str){
try{
String baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:80504' ;
HTTPRequest request = new HTTPRequest();
request.setEndpoint(baseUrl);
request.setHeader('Content-Type', 'application/json');
request.setMethod('GET');
request.setTimeout(120000);
HTTP http = new HTTP();
HTTPResponse response = http.send(request);
response.getStatusCode();
response.getBody();
GeoCodeResult geo =(GeoCodeResult)JSON.deserialize(response.getBody(),GeoCodeResult.class);
String state ='';
String city='';
if(geo.status=='OK'){
for(Results results : geo.results){
for( Address_components address : results.address_components){
if(address.types.get(0)=='locality'){
city=address.long_name;
}
else if(address.types.get(0)=='administrative_area_level_1'){
state=address.long_name;
}
}
}
system.debug('@NUR city ==='+city + ' , state == '+ state);
}
else {
system.debug('@NUR results === '+geo.status);
}
}
catch(Exception e){
String errorMessage='';
errorMessage=e.getMessage();
errorMessage+= ' ::: inside updateAddressByGeocode.getUserByEmail(string email) ....';
}
}
public class GeoCodeResult {
public List<Results> results;
public String status;
}
public class Address_components {
public String long_name;
public String short_name;
public List<String> types;
}
public class Results {
public List<Address_components> address_components;
}
}
Map<String, String>
. For more information please read JSON Methods documentation.