Skip to main content

Salesforce's JSON.deserialize Method - Full Code with Output

In modern web applications and API integrations, JSON (JavaScript Object Notation) is the standard format for exchanging data. In Salesforce Apex, converting JSON strings into strongly-typed Apex objects is streamlined using the built-in JSON.deserialize method.

In plain words: JSON.deserialize converts a raw JSON text string into a strongly-typed Apex class instance, giving you compile-time safety and dot-notation access to properties.

Understanding JSON.deserialize Syntax

The JSON.deserialize method takes a JSON formatted string along with the target Apex class type, returning an untyped Object that you explicitly cast to your wrapper type:

public static Object deserialize(String jsonString, Type apexType);
  • jsonString: The raw incoming JSON string payload.
  • apexType: The target class definition specified via TargetClassName.class syntax.

Step-by-Step Implementation

Step 1: Create the Wrapper Class

Define an Apex class matching the exact variable names and types present in your incoming JSON payload:

public class Employee {
    public String name;
    public Integer age;
    public String department;
}

Step 2: Deserialize and Access Data

Invoke JSON.deserialize within your service logic and cast the returned generic object back to your wrapper type:

public class JSONDeserializerExample {
    public static void deserializeEmployeeJSON() {
        String jsonString = '{"name": "John Doe", "age": 30, "department": "Sales"}';
        
        // Deserialize and cast to Employee object
        Employee emp = (Employee) JSON.deserialize(jsonString, Employee.class);

        // Access properties using dot notation
        System.debug('Name: ' + emp.name);
        System.debug('Age: ' + emp.age);
        System.debug('Department: ' + emp.department);
    }
}
Common Developer Mistake: Forgetting to cast the result of JSON.deserialize (e.g., (Employee)) will result in a compile error because the method signature returns generic Object type.
Execution Output: Running JSONDeserializerExample.deserializeEmployeeJSON() generates the following Apex Debug Log lines:

USER_DEBUG|[10]|DEBUG|Name: John Doe
USER_DEBUG|[11]|DEBUG|Age: 30
USER_DEBUG|[12]|DEBUG|Department: Sales
If key names in incoming JSON contain reserved Apex keywords (like date or currency), consider using JSON.deserializeUntyped() or perform string replacements before deserialization.

Conclusion

The JSON.deserialize method provides a reliable way to transform incoming JSON payloads into strongly-typed Apex objects, making web service integrations simpler and less error-prone.