Convert a JSON String To Map in Salesforce Apex

Recently, in our Salesforce Org, we were developing an application that integrates with an external API to fetch customer information. The API returns customer details in JSON format, so we have to parse this JSON string to store it in a Map for access within the Apex code.

In this Salesforce tutorial, I will explain various methods to convert a JSON string to a Map in Salesforce Apex.

JSON Handling in Salesforce

In Salesforce, handling JSON effectively is required to integrate the Salesforce org with external APIs, configure dynamic data exchanges, and manage complex metadata structures.

Parsing JSON into Maps or custom objects allows us to build efficient and maintainable Apex code while ensuring connections between the systems.

Convert JSON String to Map Using JSON.deserializeUntyped() in Salesforce Apex

To convert a JSON string to a map using the JSON.deserializeUntyped() method, navigate to the Salesforce developer console, and follow the steps below.

In the developer console, create a new Apex class, enter the code below, and save it.

public class JSONstringConversion {
    public static void convertJsonToMap() {
        
        String jsonString = '{"name": "Eva James", "age": 30, "isActive": true}';

        Map<String, Object> resultMap = (Map<String, Object>) JSON.deserializeUntyped(jsonString);

        String name = (String) resultMap.get('name');
        Integer age = (Integer) resultMap.get('age');
        Boolean isActive = (Boolean) resultMap.get('isActive');

        System.debug('Name: ' + name);
        System.debug('Age: ' + age);
        System.debug('Is Active: ' + isActive);
    }
}

In the above code, we first defined a JSON string and then deserialized the JSON to a Map using the JSON.deserializeUntyped() method.

After this, the resultMap.get() method will assess the JSON string values and then display them in a Map in the debug.

Now launch the Apex anonymous window and execute the code below to call the class method.

JSONstringConversion.convertJsonToMap();

Now, in the execution log window, we can see the Map values converted from a JSON string.

How to convert JSON string to map in Salesforce Apex

This way, convert a JSON String to a Map using the JSON.deserializeUntyped() method in Salesforce Apex.

Convert JSON String to Map Using Wrapper Class in Salesforce Apex

To convert a JSON string to a Map using a wrapper class in Salesforce Apex, navigate to the developer console and follow the steps below.

In the developer console, create a new Apex class, enter the code below, and save it.

public class ConvertList {
    public TitleWrapper titleIns { get; set; }
    public ProductWrapper productIns { get; set; }

  
    public ConvertList() {
        titleIns = new TitleWrapper();
        productIns = new ProductWrapper();
    }

    public class TitleWrapper {
        public String Ti