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; } }
Answers:
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. 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; }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0