html code

How can I process a JSON response in Apex Salesforce

Introduction

At times, I have encountered confusion regarding the process of parsing a JSON string to extract the desired value. Now, we will explore the steps involved in achieving this.

Example JSON

{
  "location_suggestions": [
    {
      "entity_type": "city",
      "entity_id": 6,
      "title": "New Delhi",
      "latitude": 17.366,
      "longitude": 78.476,
      "city_id": 6,
      "city_name": "New Delhi",
      "country_id": 1,
      "country_name": "India"
    }
  ],
  "status": "success",
  "has_more": 0,
  "has_total": 0
}
Simplified Approach

This method I discovered is the easiest among all the ones I have attempted. You can simply copy the JSON string provided above and utilize the Apex generator tool called Json2Apex to generate the corresponding Apex code.

To utilize this method, you need to paste the JSON string into the provided space. Then, give it a suitable name and click on the “generate” button. This will generate two classes, one being the main class and the other a test class. Please note that this code generation is done by the JSON2Apex tool, accessible at http://json2apex.herokuapp.com/.

public class Wrapper{

 public List location_suggestions;
 public String status;
 public Integer has_more;
 public Integer has_total;

 public class Location_suggestions {
  public String entity_type;
  public Integer entity_id;
  public String title;
  public Double latitude;
  public Double longitude;
  public Integer city_id;
  public String city_name;
  public Integer country_id;
  public String country_name;
 }

 
 public static Wrapper parse(String json) {
  return (Wrapper) System.JSON.deserialize(json, Wrapper.class);
 }
}

In the main class, when making the callout, you can pass the obtained JSON response to the parse method in the previously generated “ZomatoLocation.cls” Apex class in the following manner.

reponse = res.getBody();
ZomatoLocation jsonApex = ZomatoLocation.parse(reponse);
for(ZomatoLocation.Location_suggestions loc : jsonApex.Location_suggestions){
    System.debug('location details'+loc);
    locationList.add(loc);
}
system.debug('locationList'+locationList);

Next, iterate through the list of Location_suggestions, which can be considered similar to a custom object in Apex. Add each element to the list and utilize it wherever required in your code.