How Do I Work with JSON in Apex?

Question
This is a canonical question and answer developed by the community to help address common questions. If your question was closed as a duplicate or you were directed here, please review the resources provided and use them to refine your specific inquiry. To explore more canonical Q&A, visit the canonical-qa tag.
I need to work with JSON in Apex. Specifically, I have a JSON structure that I need to either deserialize when receiving data from a web service or serialize when sending data to another system. How can I get started with JSON handling in Apex?
Answer
JSON Serialization and Deserialization in Apex
Apex provides multiple methods for JSON serialization and deserialization, catering to both strongly-typed and dynamic data structures. This guide summarizes key approaches, including:
Typed serialization and deserialization using JSON.serialize() and JSON.deserialize()
Untyped deserialization with JSON.deserializeUntyped()
Manual handling via JSONGenerator and JSONParser
Code generation tools like JSON2Apex
This is not an exhaustive reference but an overview of key concepts and best practices, along with links to further resources.
Complex Types in Apex and JSON
JSON represents data using maps (objects) and lists (arrays), which correspond to Apex’s Map<String, Object> and List<Object>. JSON can also be mapped to Apex classes where keys become class attributes.
For example, consider the following JSON structure:
{
"errors": [ "Data failed validation rules" ],
"message": "Please edit and retry",
"details": {
"record": "001000000000001",
"record_type": "Account"
}
}This JSON includes nested objects and lists, making it a useful case study for different deserialization techniques.
Typed Serialization and Deserialization
Apex provides two key methods for working with typed JSON structures:JSON.serialize() – Converts Apex objects and collections into JSON format.JSON.deserialize() – Converts JSON strings into Apex objects of a specified class.
Example: Defining a Typed Apex Class
This JSON structure can be mapped to the following Apex class:
public class Example {
public List<String> errors;
public String message;
public class ExampleDetail {
public Id record;
public String record_type;
}
public ExampleDetail details;
}Parsing JSON into an Apex Object
Example ex = (Example) JSON.deserialize(jsonString, Example.class);Converting an Apex Object into JSON
String jsonString = JSON.serialize(ex);Handling Nested JSON Objects
Apex allows one level of inner classes, meaning deeply nested JSON structures may require defining multiple classes at the top level.
Handling JSON with Maps
If JSON represents key-value pairs dynamically, it can be deserialized into a Map<String, Example>:
Map<String, Example> exampleMap =
(Map<String, Example>) JSON.deserialize(jsonString, Map<String, Example>.class);This approach is not suitable if JSON properties contain Apex-reserved keywords or invalid identifiers (e.g., special characters or hyphens).
Additional Options for Typed Serialization:
Omitting null values
Pretty-printing JSON output
Strict deserialization (rejects unexpected attributes)
Untyped Deserialization with JSON.deserializeUntyped()
When JSON structures vary dynamically, strongly-typed classes may not be viable. The method JSON.deserializeUntyped() returns an Object, which must be cast dynamically.
Example: Handling Dynamic JSON Structures
{
"scope": "Accounts",
"data": {
"payable": 100000,
"receivable": 40000
}
}Since scope can be either a string or an object, typed classes are impractical. Instead, use untyped deserialization:
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(jsonString);Safely Accessing Nested Values
Object result = JSON.deserializeUntyped(jsonString);
if (result instanceof Map<String, Object>) {
Map<String, Object> resultMap = (Map<String, Object>) result;
if (resultMap.get('scope') == 'Accounts' &&
resultMap.get('data') instanceof Map<String, Object>) {
Map<String, Object> data = (Map<String, Object>) resultMap.get('data');
if (data.get('payable') instanceof Integer) {
Integer payable = (Integer) data.get('payable');
AccountsService.handlePayables(payable);
} else {
// Handle error
}
} else {
// Handle error
}
} else {
// Handle error
}This Apex code snippet deserializes a JSON string into an untyped object and checks if it is a Map<String, Object>. If so, it verifies that the scope key has the value "Accounts" and that the data key contains another map. Within this nested map, it checks if the payable key exists and is an Integer. If all conditions are met, it extracts the payable value and calls AccountsService.handlePayables(payable). If any condition fails, it executes an error-handling block. This approach ensures that only valid JSON structures are processed while preventing runtime errors due to unexpected data formats. However, it could be improved by handling potential null values, supporting Decimal types, and logging errors for better debugging.
Related Posts:
How to get started working with JSON in Apex?
Understanding Object and JSON Operations in LWC
Kick Start Your Career with Real-Time Project-Based Salesforce Training
Our Salesforce Course is designed to offer a deep dive into the Salesforce platform, equipping you with essential skills to thrive in the CRM industry. The program covers key modules like Salesforce Admin, Developer, and AI, blending theoretical knowledge with practical experience. Through real-world projects and hands-on tasks, you’ll develop the skills needed to solve complex business challenges with confidence using Salesforce solutions. Our expert instructors ensure you gain both technical expertise and industry insights to excel in the Salesforce ecosystem.
In addition to technical proficiency, our Salesforce Training in Dallas provides personalized mentorship, exam preparation, and interview coaching to boost your career potential. You’ll have access to a rich set of study materials, live project experience, and consistent support throughout your learning journey. By the course’s conclusion, you’ll be well-prepared for certification exams and equipped with the problem-solving skills employers seek. Take the first step towards your Salesforce career and unlock unlimited opportunities. Sign up for a Free Demo today!

