
How to get started working with JSON in Apex?

Table Of Contents
- Understand JSON Structure
- JSON Parsing in Apex
- Serializing Apex Objects to JSON
- Deserialize JSON to Apex Objects
- Best Practices
- Common Workarounds
- Frequently Asked Questions (FAQs)
JSON (JavaScript Object Notation) is a lightweight format that helps transfer data between servers and clients. In Salesforce, working with JSON is important when you need to integrate external systems. Apex, the Salesforce programming language, provides built-in tools to easily parse and generate JSON. These tools make handling data efficient and straightforward. If you want to work with APIs or automate tasks, learning how to work with JSON in Apex is a key skill.
To get started with JSON in Apex, you’ll need to know two main operations: deserialization and serialization. Deserialization converts JSON into Apex objects, and serialization converts Apex objects back into JSON. These operations allow you to exchange data between Salesforce and external applications. By mastering JSON handling in Apex, you’ll make integrations smoother and processes faster. This knowledge will help you become more effective in Salesforce development
Join our Salesforce course at CRS Info Solutions for 100% job oriented, real-time, job-oriented training and thorough preparation for certification exams. Sign up for a free demo today to kickstart your Salesforce career.
Here’s a guide to get you started:
Understand JSON Structure:
To understand JSON structure, you need to know that JSON represents data as key-value pairs, where each key is a string and the value can be a string, number, boolean, array, or another JSON object. A JSON object is enclosed in curly braces {}
and contains multiple key-value pairs. Keys are always in quotes, while values can be various data types. Arrays, enclosed in square brackets []
, store lists of values. Understanding this structure is critical when working with JSON in Apex because it allows you to effectively parse and handle complex data from external systems. Knowing how to navigate JSON structure makes it easier to manipulate data within Salesforce Apex.
Read more: Ultimate Salesforce interview questions and answers 2024.
JSON Parsing in Apex:
To parse JSON in Apex, you use the JSON
class provided by Salesforce. This class includes methods for parsing JSON content and converting it into native Apex objects.
Example:
String jsonString = '{"name":"John", "age":30}';
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
System.debug('Name: ' + parsed.get('name'));
Collection is one of the important concept, checkout: Collections in Salesforce Apex
Serializing Apex Objects to JSON:
When you need to convert an Apex object to a JSON string, use the JSON.serialize
method. This is particularly useful when you need to send data from Salesforce to an external system in JSON format.
Account acc = new Account(Name='Acme');
String jsonString = JSON.serialize(acc);
System.debug(jsonString);
Join CRS Info Solutions Salesforce online course for a career building learning experience with 100% hands-on training and real-time projects. Enroll for free demo today!
Deserialize JSON to Apex Objects:
To convert JSON content into an instance of a specific Apex class, use JSON.deserialize
.
Example
String jsonString = '{"Name":"Acme", "Phone":"1234567890"}';
Account acc = (Account) JSON.deserialize(jsonString, Account.class);
System.debug('Account Name: ' + acc.Name);
Read more: Strings in Salesforce Apex
String jsonString = '{"Name":"Acme", "Phone":"1234567890"}';
Account acc = (Account) JSON.deserialize(jsonString, Account.class);
System.debug('Account Name: ' + acc.Name);
Handling Complex JSON Structures: For more complex JSON structures, consider defining custom Apex classes that mirror the JSON structure. This approach simplifies the deserialization process.
Read more: Arrays in Salesforce Apex
Best Practices:
Always validate JSON data before parsing to ensure it’s well-formed.
Handle exceptions using try-catch blocks to manage parsing errors.
Use built-in methods like JSON.serializePretty
for better readability when debugging.
Testing JSON Operations: Ensure that your Apex classes handling JSON are well-tested. Salesforce requires a minimum of 75% code coverage for the unit tests.
Stay Updated with Salesforce Documentation: Salesforce regularly updates its platform. Keep an eye on the official Salesforce documentation for any changes or new features related to JSON handling in Apex.
Read more: Array methods in Salesforce Apex
1. Complex Types in Apex and JSON
In Apex, complex types refer to custom classes or standard Salesforce objects with nested structures. These types are often represented in JSON as objects containing other objects or arrays.
Code Example:
public class Order {
public String orderId;
public List<Item> items;
public class Item {
public String productId;
public Integer quantity;
}
}
Order order = new Order();
order.orderId = '12345';
order.items = new List<Order.Item>();
Order.Item item = new Order.Item();
item.productId = 'A1';
item.quantity = 10;
order.items.add(item);
String jsonString = JSON.serialize(order);
System.debug(jsonString);
Checkout: DML statements in Salesforce
2. Typed Serialization with JSON.serialize() and JSON.deserialize()
Serialization is the process of converting an Apex object into a JSON string.
Deserialization is converting JSON back into an Apex object.
Code Example:
// Serialization
Account acc = new Account(Name='Acme', Phone='1234567890');
String jsonString = JSON.serialize(acc);
System.debug(jsonString);
// Deserialization
String jsonInput = '{"Name":"Acme", "Phone":"1234567890"}';
Account deserializedAcc = (Account) JSON.deserialize(jsonInput, Account.class);
System.debug(deserializedAcc.Name);
Read more: Salesforce apex programming examples
3. Untyped Deserialization with JSON.deserializeUntyped()
Untyped deserialization returns a JSON structure as nested collections of primitive data types (like Map<String, Object> for JSON objects and List<Object> for JSON arrays).
Code Example:
String jsonString = '{"name":"John", "age":30}';
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
System.debug('Name: ' + parsed.get('name'));
4. Manual Implementation with JSONGenerator and JSONParser
JSONGenerator is used for manual JSON string generation, and JSONParser is for parsing.
Code Example:
public class MyClass {
@SerializedName('class')
public String classAttribute;
}
String jsonString = '{"class":"Economics"}';
MyClass obj = (MyClass) JSON.deserialize(jsonString, MyClass.class);
System.debug(obj.classAttribute);
5. Generating Code with JSON2Apex
JSON2Apex is a tool to generate Apex classes from JSON. It’s useful for creating strongly typed classes that represent a JSON structure.
Checkout: Data types in Salesforce Apex
Common Workarounds
JSON Attribute is a Reserved Word or Invalid Identifier
If a JSON attribute name is a reserved word in Apex or an invalid identifier, use the @SerializedName
annotation.
Code Example:
public class MyClass {
@SerializedName('class')
public String classAttribute;
}
String jsonString = '{"class":"Economics"}';
MyClass obj = (MyClass) JSON.deserialize(jsonString, MyClass.class);
System.debug(obj.classAttribute);
These explanations and examples should provide a comprehensive understanding of handling JSON in Apex, from simple serialization and deserialization to dealing with complex types and common challenges. Remember, practice with these concepts in your Salesforce environment to build proficiency.
Checkout: Variables in Salesforce Apex
Frequently Asked Questions (FAQs)
1. How to get values from a JSON object in Apex?
To get values from a JSON object in Apex, you first need to deserialize the JSON string into an Apex object or a Map. You can use the JSON.deserialize
method to convert the JSON string into an Apex class instance. Once deserialized, you can access the values using dot notation. For example:
String jsonString = '{"name": "John", "age": 30}';
Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
String name = (String) jsonMap.get('name');
Integer age = (Integer) jsonMap.get('age');
2. How to deserialize JSON in Apex Salesforce?
To deserialize JSON in Apex Salesforce, you can use the JSON.deserialize
or JSON.deserializeUntyped
methods. The JSON.deserialize
method is used to convert JSON strings into specific Apex classes, while JSON.deserializeUntyped
converts JSON into a generic Map<String, Object>
. Here’s an example using both methods:
// Using a specific Apex class
public class Person {
public String name;
public Integer age;
}
String jsonString = '{"name": "John", "age": 30}';
Person person = (Person) JSON.deserialize(jsonString, Person.class);
// Using a generic Map
Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
3. How to parse JSON in Salesforce?
Parsing JSON in Salesforce involves converting JSON strings into Apex objects. You can achieve this using the JSON.deserialize
or JSON.deserializeUntyped
methods. For complex JSON structures, it’s best to create corresponding Apex classes that match the JSON structure and use JSON.deserialize
to convert the JSON string into these classes. For simpler structures, you can use JSON.deserializeUntyped
to convert JSON into a Map or List.
4. How to create JSON dynamically in Apex?
To create JSON dynamically in Apex, you can use the JSONGenerator
class. This class allows you to construct JSON strings programmatically by adding fields and values. Here’s an example:
JSONGenerator generator = JSON.createGenerator(true);
generator.writeStartObject();
generator.writeStringField('name', 'John');
generator.writeNumberField('age', 30);
generator.writeEndObject();
String jsonString = generator.getAsString();
5. What is the difference between parse and deserialize JSON?
In the context of Apex, parsing and deserializing JSON are often used interchangeably, but they have subtle differences. Parsing generally refers to reading and interpreting JSON data, which could involve converting JSON into a Map
or List
. Deserializing specifically refers to converting JSON strings into Apex objects using the JSON.deserialize
method. Deserialization is a type of parsing with a more specific goal of creating strongly-typed objects.
6. How to retrieve data from a JSON object?
To retrieve data from a JSON object in Apex, you first need to deserialize the JSON string into a corresponding Apex object or a Map
. Once deserialized, you can access the data using the appropriate keys or properties. For example:
String jsonString = '{"name": "John", "age": 30}';
Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
String name = (String) jsonMap.get('name');
Integer age = (Integer) jsonMap.get('age');
7. How to deserialize JSON?
Deserializing JSON in Apex involves converting a JSON string into an Apex object using the JSON.deserialize
or JSON.deserializeUntyped
methods. For a specific Apex class, use JSON.deserialize
, and for generic structures, use JSON.deserializeUntyped
. Example:
String jsonString = '{"name": "John", "age": 30}';
Person person = (Person) JSON.deserialize(jsonString, Person.class);
8. How to read a JSON array in Apex?
To read a JSON array in Apex, deserialize the JSON string into a List of objects or a List of Maps. Here’s an example:
String jsonArrayString = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';
List<Map<String, Object>> jsonList = (List<Map<String, Object>>) JSON.deserializeUntyped(jsonArrayString);
for (Map<String, Object> item : jsonList) {
String name = (String) item.get('name');
Integer age = (Integer) item.get('age');
}
9. How to get values from an object in Apex?
To get values from an object in Apex, you can use dot notation if you have a strongly-typed object or use the get
method if you’re working with a Map
. For example:
Person person = new Person();
person.name = 'John';
person.age = 30;
String name = person.name;
Integer age = person.age;
// Using a Map
Map<String, Object> personMap = new Map<String, Object>{'name' => 'John', 'age' => 30};
String mapName = (String) personMap.get('name');
Integer mapAge = (Integer) personMap.get('age');
10. What is the date format in JSON Apex?
The date format in JSON for Apex typically follows the ISO 8601 standard, which is yyyy-MM-dd'T'HH:mm:ss'Z'
for date-time values. When serializing or deserializing dates in JSON, Apex will use this format by default.
11. How to read JSON array values?
To read JSON array values in Apex, deserialize the JSON string into a List. You can then iterate over the list and access each element. For example:
String jsonArrayString = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';
List<Map<String, Object>> jsonList = (List<Map<String, Object>>) JSON.deserializeUntyped(jsonArrayString);
for (Map<String, Object> item : jsonList) {
String name = (String) item.get('name');
Integer age = (Integer) item.get('age');
}