html code

How to Handle JSON Response Parsing in Salesforce Apex


There have been instances when I faced confusion regarding the process of parsing a JSON string to extract the necessary value. Let’s now 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 ea

##This is easy method of all I tried Copy the above JSON String and generate Apex using this apex generator tool.

Json2Apex Generator

json to apex converter

paste the JSON string the space given, give a desirable name and click on the generate button. It generates two classes i.e both class and test class.

// // Generated by JSON2Apex //

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);

Within the primary class responsible for making the callout, transmit the acquired JSON response to the parsing method within the previously generated ZomatoLocation.cls Apex class, in the manner depicted below.

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

Furthermore, loop through the array of objects of type “Location_suggestions” (analogous to a custom object in Apex), append them to the list, and employ them wherever required.

I trust this article has provided you with valuable insights. If you find the content beneficial, I encourage you to show your support by liking my page and sharing your feedback. Your input will inspire me to create more informative posts.

Be sure to subscribe to receive the most recent updates directly delivered to your inbox.

Dated: 10, 08, 2023