Serialization and Deserialization in Apex: A Beginner’s Guide

In Salesforce development, working with data is essential, and often, you’ll need to transfer data between different systems, save it, or retrieve it. Two important concepts that help in this process are serialization and deserialization.

In this article, we will cover what serialization and deserialization mean, the role of JSON in these processes, and how to use them in Apex. We’ll also look at why the data type of variables is crucial when performing serialization and deserialization.


1. What is Serialization and Deserialization?

Serialization

Serialization is the process of converting an object into a format that can be easily stored or transmitted. For example, you might want to send data from one system to another, and serialization converts complex data into a simpler format like a string or a JSON object.

In simple terms, serialization turns your complex Apex objects into a string format.

Deserialization

Deserialization is the reverse of serialization. It’s the process of converting the serialized (string) data back into an object that your program can work with. This is useful when retrieving data from external systems or APIs.


2. What is JSON and How Does It Help?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It is one of the most commonly used formats for serialization and deserialization because of its simplicity and compatibility across different platforms.

In Salesforce, JSON is often used to serialize and deserialize data when working with APIs or sending data between systems.

Example of a JSON Object:

{
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

Here, we have a simple JSON object that represents a person with fields like name, age, and email. This can be easily serialized into a string and later deserialized back into an object in Apex.


3. Serialization and Deserialization in Apex

Apex provides several built-in methods to handle serialization and deserialization, making it easy to convert objects to and from JSON.

JSON.serialize()

The JSON.serialize() method converts an Apex object into a JSON string. This is useful when you need to send data to an external system or save it in a format that can be easily stored.

Example:

public class Person {
    public String name;
    public Integer age;
    
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Person person = new Person('John Doe', 30);
String serializedData = JSON.serialize(person);
System.debug(serializedData); // Output: {"name":"John Doe","age":30}

In this example, we create a Person object and use JSON.serialize() to convert it into a JSON string.

JSON.deserialize()

The JSON.deserialize() method converts a JSON string back into an Apex object. This is useful when you receive JSON data from an external source and need to convert it back into an Apex object for manipulation.

Example:

String jsonData = '{"name":"John Doe","age":30}';
Person deserializedPerson = (Person) JSON.deserialize(jsonData, Person.class);
System.debug(deserializedPerson.name); // Output: John Doe
System.debug(deserializedPerson.age);  // Output: 30

Here, we take a JSON string and use JSON.deserialize() to convert it back into a Person object.

JSON.deserializeUntyped()

In some cases, you may not know the exact type of data you’re deserializing. In such cases, you can use the JSON.deserializeUntyped() method, which converts the JSON into a generic Map<String, Object> or List<Object>.

Example:

String jsonData = '{"name":"John Doe","age":30}';
Map<String, Object> dataMap = (Map<String, Object>) JSON.deserializeUntyped(jsonData);
System.debug(dataMap.get('name')); // Output: John Doe
System.debug(dataMap.get('age'));  // Output: 30

4. How Data Types Impact Serialization and Deserialization

The data type of variables plays a crucial role during serialization and deserialization because Apex needs to know how to convert objects to and from JSON. If the data types don’t match, you may encounter errors.

For example:

  • If you’re deserializing a string into an object, you must ensure the JSON structure matches the structure of the object.
  • If you use the wrong data type (e.g., trying to deserialize an Integer as a String), you will get errors.

Example of Data Type Mismatch:

String jsonData = '{"name":"John Doe","age":"thirty"}'; // 'age' should be an integer, but it's a string
Person person = (Person) JSON.deserialize(jsonData, Person.class); // This will throw an error

To avoid errors, ensure that the JSON data and Apex object have matching fields and data types.


5. Example: Serialization and Deserialization in Action

Let’s look at an example where we serialize a list of contacts and then deserialize them back into Apex objects.

Serialization Example:

List<Contact> contactList = [SELECT Id, Name, Email FROM Contact LIMIT 5];
String serializedContacts = JSON.serialize(contactList);
System.debug(serializedContacts); 

Deserialization Example:

String jsonContacts = '[{"Id":"0031I00001F9H4aQAF","Name":"Jane Doe","Email":"jane.doe@example.com"}]';
List<Contact> contactList = (List<Contact>) JSON.deserialize(jsonContacts, List<Contact>.class);
System.debug(contactList[0].Name); // Output: Jane Doe

Conclusion

Serialization and deserialization are essential concepts in Salesforce development that allow you to easily convert objects to a format that can be transferred, stored, or processed. JSON is a popular format used in these processes because of its simplicity and platform independence.

By mastering these concepts in Apex, you’ll be able to efficiently work with external systems, transfer data, and build more robust integrations.