3

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;
}
}
4
  • Have you tried to deserialize the JSON string in Apex via JSON.deserialize method? You can simply desierialize it to a Map<String, String>. For more information please read JSON Methods documentation. Commented Jun 19, 2014 at 4:45
  • I've created a simple wrapper class for it (not all fields, just the ones I needed) at stackoverflow.com/questions/3122038/…, maybe you'll find it useful.
    – eyescream
    Commented Jun 19, 2014 at 6:30
  • Thanks @eyescream ... based on your answer there.I get to know that we can choose to create object with selected field and not necessary to create all fields that returned by JSON.
    – unidha
    Commented Jun 23, 2014 at 2:51
  • It seem like we cannot choose which field that we want to deserialize.For example I only create field for address_component but it throw JSONException saying format_address , geometry etc. are unknown field.Now need to extract and create field for all JSON element that return.
    – unidha
    Commented Jun 25, 2014 at 9:24

2 Answers 2

11

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.

4
  • Thanks a lot @Bachovski. This is what I need, at least I get the structure of JSON object that returned from Google API.
    – unidha
    Commented Jun 23, 2014 at 2:48
  • Not a problem. I learned the hard way :) Commented Jun 23, 2014 at 2:51
  • Out of curiosity what happens if the JSON format being received is modified to have additional parameters. Will the casting to this wrapper class ignore the extra and just store what it can or will it cause the cast to fail.
    – Chris
    Commented Jan 10, 2015 at 17:27
  • This is pretty awesome!
    – manza
    Commented May 21, 2016 at 23:44
0

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.
                parser.skipChildren();
            }
        }
    }
}
} 

// 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;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .