Kishore
Kishore I am a Salesforce developer and a so-called blogger at SalesforceLwc.in. I love learning and sharing.

How to Parse JSON Response in Apex Salesforce

How to Parse JSON Response in Apex Salesforce

Summary

There are times when I was confused about how to parse a JSON string so that I could get the required value. Now we will see how it can be done.

##Sample 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 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 http://json2apex.herokuapp.com/ //

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 main class where you are making the callout, pass the JSON response obtained to the parse method in the above generated ZomatoLocation.cls apex class as follows.

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


and iterate through the list of type Location_suggestions (similar to a custom object in apex), add them to the list and use wherever needed.

Hope this post helped you gain some knowledge, If you like the content please don’t step back to like my page and leave your feedback, It will motivate me to make more posts.

Subscribe to receive the latest updates directly in your inbox.

-->
-->