How to Decode JSON Response in Apex Salesforce.

Synopsis

There have been instances when I found myself uncertain about the process of parsing a JSON string to extract the desired information. Now, let’s explore how this can be accomplished.

Example JSON

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

This is the simplest method I’ve attempted so far. Just copy the JSON string above and utilize the Apex generator tool to automatically generate Apex code.

Json2Apex Generator

Paste the JSON string into the provided space, assign a suitable name, and then click the “generate” button. This action will produce two classes, including both the main class and its corresponding test class.

public class Test {

 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 Test parse(String json) {
  return (Test) System.JSON.deserialize(json, Test.class);
 }
}

In the primary class where you’re making the callout, transmit the acquired JSON response to the parse method within 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);

Then, iterate through the list of “Location_suggestions” types (which are akin to custom objects in Apex), append them to the list, and employ them as required.