Simple way to generate object from JSON that return from Google Geocode API?

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){


    String baseUrl = ''  ;

    HTTPRequest request = new HTTPRequest();              
    request.setHeader('Content-Type', 'application/json');

    HTTP http = new HTTP();
    HTTPResponse  response =  http.send(request);    

   GeoCodeResult geo =(GeoCodeResult)JSON.deserialize(response.getBody(),GeoCodeResult.class);

   String state ='';
   String city='';


         for(Results results : geo.results){

             for( Address_components address :  results.address_components){
                 else if(address.types.get(0)=='administrative_area_level_1'){

         system.debug('@NUR city ==='+city + ' , state == '+ state);

   else {
       system.debug('@NUR results === '+geo.status);


 catch(Exception e){
       String errorMessage='';
       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;


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Copy and paste the JSON example here. This will generate wrapper classes for your JSON objects and you’ll be able to just de-serialize the JSON String from the response into those classes.

However, sometimes when you have dynamic keys in your JSON string, this method will not work. You will then need to manually parse that String using the JSON Parser methods in APEX.

Method 2

JSON is supported out of box in apex.

Take a look at this example from documentation. Link

public static void parseJSONString() {
String jsonStr = 
    '{"invoiceList":[' +
    '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
        '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
        '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
            '"invoiceNumber":1},' +
    '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
        '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
        '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
        '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +

// Parse entire JSON response.
JSONParser parser = JSON.createParser(jsonStr);
while (parser.nextToken() != null) {
    // Start at the array of invoices.
    if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
        while (parser.nextToken() != null) {
            // Advance to the start object marker to
            //  find next invoice statement object.
            if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                // Read entire invoice object, including its array of line items.
                Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
                system.debug('Invoice number: ' + inv.invoiceNumber);
                system.debug('Size of list items: ' + inv.lineItems.size());
                // For debugging purposes, serialize again to verify what was parsed.
                String s = JSON.serialize(inv);
                system.debug('Serialized invoice: ' + s);

                // Skip the child start array and start object markers.

// Inner classes used for serialization by readValuesAs(). 

public class Invoice {
public Double totalPrice;
public DateTime statementDate;
public Long invoiceNumber;
List<LineItem> lineItems;

public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
    totalPrice = price;
    statementDate = dt;
    invoiceNumber = invNumber;
    lineItems = liList.clone();

public class LineItem {
public Double unitPrice;
public Double quantity;
public String productName;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x