Apex/VisualForce

JSON2Apex tool

In Salesforce, if you need to consume web services – you will have to make either SOAP or REST Callouts. With SOAP protocol, you have to follow some specific steps such as importing the WSDL of the service using the tool WSDL2Apex provided by salesforce themselves and it generates classes which handles the complexity of handling the response back in XML form and hence eases the response handling. In case of REST callouts, the response comes back as JSON (JavaScript Object Notation) string and we do not have a salesforce provided tool to generate Apex classes which can handle the complexity of parsing the response for us as JSON strings do not have specific standards and varies a lot. But luckily, there is a tool developed by Simon Fell and Pat Patterson called as JSON2Apex which completely minimizes the work for JSON parsing in the code. Thanks to them for this great tool !!!.

To begin with on how to use this tool, follow the below steps – I am going to write an Apex class which will call a web service from GeoNames and retrieves a list of all the recent earthquakes near to a place provided by latitude and longitude co-ordinates. For the demo purpose, I will use a hard-coded endpoint which returns few nearby earthquake records as JSON string.

a) Click this link JSON recent earthquakes and it will take you to the JSON string response – copy the content.

b) Click this link JSON2Apex and it will open the JSON2Apex tool. Paste the content from above step in the box and click ‘Create Apex‘ button. You can also give a meaningful name of the Apex class to be generated as per your naming conventions. Leave the checkbox ‘create explicit parse code‘ unchecked. This is needed to look at the details of how the parsing is being carried and we will not use for our demo. This steps will download a zip file containing 2 classes – an Apex class having the string JSON parse logic and it’s Apex test class as well – so you do not have to worry about writing a test class for this new external classes. Copy their content and create classes in your org.

c) You would notice that since this sample JSON contains a reserve keyword ‘datetime‘ in it’s string representation – the same was carried over to JSON2Apex class and hence needs update. Simply rename the keyword to something else such as ‘gdatetime‘ as done here.

d) Below are the apex classes which shows how easy it is to parse the JSON response with the help from using the tool, otherwise it would have been tough and took longer to develop the code using JSON class parser or using deserializedUntyped methods.

e) Lastly, do not forget to add the GeoNames website to your Remote Site Settings, otherwise salesforce will not allow the callouts due to security.

Feel Free to provide your valuable comments or point out any issues or scope of improvement in the above code.