Ways to Deserialize Apex

By in
2798
Ways to Deserialize Apex

Common Deserialization Techniques

When it comes to integrations with Salesforce, deserialization plays a very vital role in connecting two different systems. REST API is very widely used nowadays. It can send data using JSON, also known as JavaScript Object Notation.

 

Deserializing a Specific Sobject Type

Syntax:

public static Object deserialize(String jsonString, System.Type apexType)

 

If we know that the response data is of specific Sobject Type then it’s very simple to extract information from it.

For example, the data is of Account Sobject Type, then we can simply write the following line to access its contents.

 

String incomingJSON = ‘{“Name”: “White Gloves”, “Is Active” : true}’

Account acc = JSON.deserialize(incomingJSON, Account.class);

 

Now with the acc variable we can access the Name property like, acc.Name.

 

Deserializing a JSON using Wrapper Class

A wrapper class is just like any other class in Salesforce whose purpose is to act as a custom data type for Lightning Components or a JSON received through integration.

Syntax:

public static Object deserialize(String jsonString, System.Type apexType)

 

Now let’s assume that the incoming JSON looks like this,

String incomingJSON = ‘{“Name”: “White Gloves”, “Is Active” : true}’;

And we do not know have any predefined type of JSON in the system, then we can create our own type like this,

 

public class IntegrationWrapper {

String Name;

Boolean IsActive;

}

 

IntegrationWrapper data = JSON.deserialize(incomingJSON, IntegrationWrapper.class);

Similarly, we can access the properties just like any other object.

 

String nam = data.Name;

 

Conclusion

While deserializing JSON strings, it’s helpful if you already know the type of data that the JSON can fit into. For example, any of your Standard or Custom Objects – if not, you can just create a wrapper and cast the JSON into it.

 

Additional Resources:

Cover Photo by Alina Grubnyak on Unsplash

Leave a reply

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