How Do I Get Started Working with JSON in Apex?

How Do I Get Started Working with JSON in Apex?

On February 8, 2025, Posted by , In Salesforce Technical Questions, With Comments Off on How Do I Get Started Working with JSON in Apex?
Salesforce Technical Questions with Answers Apex, LWC, Marketing Cloud

Question:

I have a specific JSON structure in mind that I need to work with. The goal is to either deserialize a JSON string coming in from a web service into an Apex object or serialize Apex data into a JSON string for sending it to another system. How should I get started with handling JSON in Apex? Are there any tools, techniques, or best practices that can make this process easier?

Answer:

Working with JSON in Apex is straightforward, thanks to built-in classes like JSON, JSONGenerator, and JSONParser. Below are detailed explanations and examples to help you get started.

Get expert Salesforce certification guidance, interview prep, and hands-on Salesforce Online Training — Sign up for a free demo today!

Understand JSON Basics

JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. It consists of key-value pairs, where keys are strings and values can be strings, numbers, arrays, or objects. JSON is easy to read and write, making it a popular choice for APIs and web services.

Use the JSON Class in Apex

In most cases, the JSON class is sufficient for serializing and deserializing JSON. Here’s how you can use it:

Example: Serializing an Apex Map into JSON

Map<String, Object> root = new Map<String, Object>{
    'awkward key' => 'awkward with "quotes" value',
    'nested object key' => new Map<String, Object>{
        'key1' => 'value1',
        'key2' => true,
        'key3' => 123.456,
        'key4' => null
    },
    'nested array key' => new List<Map<String, Object>>{
        new Map<String, Object>{
            'another key1' => 'value1',
            'another key2' => true
        },
        new Map<String, Object>{
            'another key1' => 'value2',
            'another key2' => false
        }
    }
};

String jsonString = JSON.serializePretty(root);
System.debug(jsonString);

Explanation : The provided code creates a nested map structure in Salesforce Apex, where the root map contains keys with various data types as values, including strings, a nested map, and a list of maps. The nested map holds different key-value pairs, including a string, boolean, number, and null. The nested array key contains a list of maps, each with its own key-value pairs. Finally, the map is serialized into a pretty-formatted JSON string using JSON.serializePretty() and logged using System.debug().

Output Explanation:

The JSON produced will look like this:

{
  "nested array key": [
    {
      "another key2": true,
      "another key1": "value1"
    },
    {
      "another key2": false,
      "another key1": "value2"
    }
  ],
  "nested object key": {
    "key4": null,
    "key3": 123.456,
    "key2": true,
    "key1": "value1"
  },
  "awkward key": "awkward with \"quotes\" value"
}

Explanation : This JSON structure contains three main components: a nested array under the key "nested array key", which holds two objects with boolean and string values; a nested object under the key "nested object key", containing a mix of data types like null, number, boolean, and string; and a key "awkward key" with a string value that includes escaped quotes within it. Each key is associated with values of various types, demonstrating JSON’s ability to store diverse data structures.

Applications

This JSON structure can be used in scenarios like:

  • Transmitting configuration settings in a web service.
  • Storing hierarchical data, such as user preferences or product details.
  • Serializing complex data structures in an API response.

If this JSON structure were being processed in Apex, the deserialization would map these keys and values into corresponding objects, lists, or maps.

Deserialize JSON to Apex Objects

For simple JSON structures, you can use JSON.deserialize or JSON.deserializeUntyped.

Example:
Parsing JSON into a Map

String jsonString = '{"name":"Acme Corporation","industry":"Manufacturing"}';
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(jsonString);
System.debug('Name: ' + data.get('name')); // Output: Name: Acme Corporation
System.debug('Industry: ' + data.get('industry')); // Output: Industry: Manufacturing

Explanation : The given code snippet deserializes a JSON string into a Map in Salesforce Apex. The JSON.deserializeUntyped method is used to parse the JSON string, resulting in a generic Map<String, Object> where the keys are strings and the values are objects

Generate Apex Classes for Complex JSON

To generate Apex classes for complex JSON in Salesforce, use the JSON2Apex tool or the Generate from JSON feature in the Developer Console. These tools automatically create Apex classes that match the structure of your JSON data. This simplifies the process of working with JSON in Apex, especially when dealing with nested or complex objects.

Example:
Using Generated Classes

Given the JSON:

{
  "name": "Acme Corporation",
  "industry": "Manufacturing",
  "employees": [
    { "id": 1, "name": "John Doe" },
    { "id": 2, "name": "Jane Smith" }
  ]
}

Explanation : The provided JSON represents data for a company named “Acme Corporation,” which operates in the “Manufacturing” industry. It includes a list of employees, with each employee having an id and name. Specifically, the company has two employees: John Doe (id: 1) and Jane Smith (id: 2).

The given JSON structure represents data in a hierarchical format, commonly used for data interchange between systems. Let’s break it down step by step:

The generated class would look like this:
public class Root {
    public String name;
    public String industry;
    public List<Employee> employees;

    public class Employee {
        public Integer id;
        public String name;
    }
}

Explanation : The Root class contains three fields: name, industry, and a list of Employee objects. The inner Employee class has two fields: id and name, representing individual employee details.

You can deserialize JSON into this class like so:

String jsonString = '{"name":"Acme Corporation","industry":"Manufacturing","employees":[{"id":1,"name":"John Doe"},{"id":2,"name":"Jane Smith"}]}';
Root data = (Root) JSON.deserialize(jsonString, Root.class);
System.debug('Company: ' + data.name); // Output: Company: Acme Corporation

Explanation : The code defines a JSON string representing a company with employees, then deserializes it into a custom Apex class Root. The System.debug statement outputs the name field from the deserialized object, showing the company’s name, “Acme Corporation.”

Handling Keys That Aren’t Valid Apex Identifiers

Sometimes JSON keys may contain spaces or special characters that cannot directly map to Apex variables. In such cases, using a Map<String, Object> is a practical solution.

When to Use JSONGenerator and JSONParser

While the JSON class is suitable for most scenarios, the JSONGenerator and JSONParser classes provide fine-grained control. For example, if you need to generate JSON incrementally or parse large JSON structures without loading the entire data into memory, these classes can be helpful.

By following these practices and leveraging Apex’s JSON handling capabilities, you can work efficiently with JSON data in your projects. If you encounter specific challenges, revisit these examples or refine your questions for further clarification.

Summing Up:

Working with JSON in Apex is crucial for integrating Salesforce with external systems, as JSON is widely used in modern APIs. The JSON class in Apex provides powerful methods for serializing Apex objects and deserializing JSON, while using Map<String, Object> offers flexibility for handling dynamic or irregular data structures. Mastering these tools, along with resources like JSON2Apex for generating tailored classes, enables efficient data processing and integration.

Comprehensive Salesforce Training in Pune

Our program offers expert-led certification guidance, advanced interview preparation, and specialized modules for Admin, Developer, and AI tracks. Salesforce training in Pune With detailed class notes, hands-on practical sessions, and industry-focused learning, we equip you to excel in the job market. Experience the difference with our high-quality training—join our free demo class today and take the first step towards success!

Related Posts :

Comments are closed.