Parsing JSON in Apex (Salesforce): A Complete Guide

Introduction to JSON and Apex

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text-based format that uses a simple syntax to represent data in a structured way. JSON is widely used in web development and has become a popular alternative to XML for data exchange between systems.

Apex is a proprietary programming language used for the Salesforce platform. Apex is a strongly-typed, object-oriented programming language that enables developers to write and execute code on the Salesforce platform. Apex provides a variety of built-in classes and methods for working with data, including methods for parsing JSON.

Understanding the JSON structure and syntax

JSON data is organized in key-value pairs, where each key represents a field name and each value represents the field’s corresponding value. JSON data is enclosed in curly braces {} and separated by commas.

A JSON object is a collection of key-value pairs, where each key is a string and each value can be a string, number, boolean, null, or another JSON object.

A JSON array is a collection of values, where each value can be a string, number, boolean, null, or another JSON object. JSON arrays are enclosed in square brackets [].

Here is an example of a JSON object:

  "name": "John Smith",
  "age": 35,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  "phoneNumbers": [
      "type": "home",
      "number": "555-555-1234"
      "type": "work",
      "number": "555-555-5678"

In this example, the JSON object has four keys (name, age, address, and phoneNumbers) and their corresponding values. The value of the “address” key is another JSON object, and the value of the “phoneNumbers” key is a JSON array.

Parsing JSON in Apex Salesforce using the JSON.deserialize method

Apex provides a built-in method called JSON.deserialize to parse JSON data and convert it into an Apex object. The JSON.deserialize method takes a single argument, which is the JSON data to be parsed, and returns an object of the specified type.

Here is an example of how to use the JSON.deserialize method to parse a JSON object:

// Define a class to hold the parsed JSON data
public class Person {
    public String name;
    public Integer age;
    public Address address;
    public List<PhoneNumber> phoneNumbers;

public class Address {
    public String street;
    public String city;
    public String state;
    public String zip;

public class PhoneNumber {
    public String type;
    public String number;

// Parse the JSON data
String jsonString = '{"name":"John Smith","age":35,"address":{"street":"123 Main St","city":"Anytown","state":"CA","zip":"12345"},"phoneNumbers":[{"type":"home","number":"555-555-1234"},{"type":"work","number":"555-555-5678"}]}';
Person p = (Person)JSON.deserialize(jsonString, Person.class);

In this example, the JSON.deserialize method is used to parse the JSON data and convert it into an instance of the Person class. The Person class has fields that match the keys in the JSON object, so the JSON data is automatically mapped to the fields of the class.

Handling errors and exceptions when parsing JSON in Apex Salesforce

The JSON.deserialize method will throw a JSONException if the JSON data cannot be parsed or if the data does not match the fields of the specified class. It is important to handle these errors and exceptions properly in your code to prevent unexpected behavior.

You can handle errors and exceptions when parsing JSON in Apex Salesforce using a try-catch block, like this:

try {
    Person p = (Person)JSON.deserialize(jsonString, Person.class);
} catch (JSONException e) {
    // Handle the error

In this example, the try block contains the code to parse the JSON data, and the catch block contains the code to handle any errors or exceptions that may occur. It’s a good practice to include proper error handling to make sure that the code is robust and can handle unexpected situations.

Examples of parsing JSON in Apex Salesforce

Parsing JSON Response in Apex

// JSON String Data
"ContactList": [
            "LastName": "Samal",
            "Email": "",
            "Mobile": "9999999999"
            "LastName": "Samal",
            "Email": "",
            "Mobile": "8888888888"

// Apex class
public class JsonParseringClass
    //Method To Parse JSON Data
    public ContactList getJSONData()
        ContactList conList = new ContactList();
        //JSON String
        String jsonString = '{"ContactList": [' +
           '{"FirstName":"Biswajeet", "LastName": 
           "Samal", "Email": "", "Mobile": 
           "9999999999"},'+ '{"FirstName":"Abhijeet", 
           "LastName": "Samal", "Email":""  
           , "Mobile": "8888888888"}]}';
        //Parse JSON to ContactList
        conList = 
        System.debug('Respone- ' + conList);
        return conList;
    public class ContactList
        public List<ContactWrapper> ContactList;
    public class ContactWrapper
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Mobile { get; set; }

Parsing JSON Response from a Web Service Callout

//API Data
    "status": "OK",
    "message": "",
    "zones": [
            "countryCode": "CI",
            "countryName": "C\u00f4te d'Ivoire",
            "zoneName": "Africa\/Abidjan",
            "gmtOffset": 0,
            "timestamp": 1642527697
            "countryCode": "GH",
            "countryName": "Ghana",
            "zoneName": "Africa\/Accra",
            "gmtOffset": 0,
            "timestamp": 1642527697
            "countryCode": "ET",
            "countryName": "Ethiopia",
            "zoneName": "Africa\/Addis_Ababa",
            "gmtOffset": 10800,
            "timestamp": 1642538497
            "countryCode": "DZ",
            "countryName": "Algeria",
            "zoneName": "Africa\/Algiers",
            "gmtOffset": 3600,
            "timestamp": 1642531297

// Generated by JSON2Apex 
public class JSON2Apex {
    public String status;
    public String message;
    public List<Zones> zones;
    public class Zones {
        public String countryCode;
        public String countryName;
        public String zoneName;
        public Integer gmtOffset;
        public Integer timestamp;

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

// Parse Data
public class GetZoneData {
    public List<SelectOption> getItems(){
       List<SelectOption> options = new List
        Http ht =new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('Endpoint url');
        HttpResponse res = ht.send(req);
        JSON2Apex obj = JSON2Apex.parse(res.getBody());
        System.debug('message => ' +obj.message);
        System.debug('status => ' +obj.status);
        for(JSON2Apex.Zones zone : obj.zones){
           options.add(new SelectOption(String.valueOf
       return options;

Conclusion and best practices for parsing JSON in Apex Salesforce

Parsing JSON in Apex Salesforce is a simple and straightforward process using the JSON.deserialize method. By following a few best practices and handling errors and exceptions properly, you can ensure that your code is robust and can handle unexpected situations.

It’s always a good practice to validate the JSON data before parsing it, this can be done by using a JSON schema validator or by checking if the JSON is well-formed. Another good practice is to use the appropriate data type for each field, this will avoid unnecessary type conversions and improve the performance. Finally, consider using a library like JSON2Apex, which can generate Apex classes from JSON data, this will save you time and effort in defining the classes to match the JSON structure.

Related Question






Leave a Reply

Your email address will not be published. Required fields are marked *