How to Convert JSON to String in Salesforce Apex

As a Salesforce developer, I recently worked on integrating our Salesforce org with an e-commerce platform. The eCommerce service provides product details in JSON format via an API. To display these details in Salesforce, I need to convert the JSON response into a string for processing.

In this Salesforce tutorial, I will explain the method of converting JSON to a String in Salesforce Apex.

Convert JSON to String in Salesforce Apex

In Salesforce Apex, the most common method for converting JSON to a string is JSON.serialize() method. In the steps below, we will convert JSON to a string using the serialize() method.

Open the anonymous apex window, enter the code below, and click the Execute button.

    Account acc = new Account(Name = 'Test Account', Phone = '87-576-9990');
    
    String prettyJsonString = JSON.serializePretty(acc);
    System.debug('Pretty JSON String: ' + prettyJsonString);

    In the above code, Account acc creates an Apex object. Then, String jsonString = JSON.serialize(acc) converts the apex object to a JSON string.

    In the execution log window, select the checkbox to debug only. Then, in the debug out, you will see the JSON strings.

      Convert Json to string in Salesforce Apex

      We can use the serializePretty() method to improve the readability of the JSON strings. To do that, run the code below in the anonymous window.

        Account acc = new Account(Name = 'Test Account', Phone = '123-456-7890');
        String prettyJsonString = JSON.serializePretty(acc);
        System.debug('Pretty JSON String: ' + prettyJsonString);

        The output in the execution log will appear as displayed in the image below.

        How to convert Json to string in Salesforce Apex

        This way, we can convert JSON to strings in Salesforce Apex by following the above steps.

        Convert JSON to a String using the Parse method in Salesforce Apex

        To convert JSON to a String in Salesforce Apex, we can use the JSONParser class to parse JSON data and extract it as a string.

        To convert the JSON to a string using the parse method, navigate to the developer console and follow the steps below.

        Open the anonymous Apex window, enter the code below, and click the Execute button.

          String jsonString = '{"name":"John","age":30}';
          JSONParser parser = JSON.createParser(jsonString);
          
          while (parser.nextToken() != null) {
              System.debug('JSON Token: ' + parser.getText());
          }

          In the execution log window, click on the checkbox debug only; then, we will see the output as JSON parsed into a string in the debug.

            Convert JSON to string using Parse in Salesforce Apex

            This way, we can convert JSON to a string using the parse method in Salesforce Apex.

            Convert JSON to a String using the Deserialize method in Salesforce Apex

            In Salesforce Apex, the JSON.deserialize() method is used to convert a JSON string back to an Apex object. It can also be used with JSON.serialize() to obtain a string representation.

            Follow the below steps to convert JSON to string in Salesforce using the JSON.deserialize() method.

            public class Account {
                public String name;
                public Integer age;
            }
            String jsonString = '{"name":"Andrew","age":25}';
            Account deserializedObj = (Account)JSON.deserialize(jsonString, Account.class);
            String jsonFromDeserialized = JSON.serialize(deserializedObj);
            System.debug(jsonFromDeserialized);

            In the above code, the JSON string {“name”:”Andrew”,”age”:25} is deserialized into an Account object using the JSON.deserialize method. Then it is serialized back into a JSON string using JSON.serialize.

            In the execution log window, select the checkbox to debug only, and you will see the JSON converted to a String object.

            JSON to String using deserialize method in Salesforce Apex

            This way, we can convert JSON to a string using the deserialize method in Salesforce Apex using JSON.deserialize() method.

            Convert JSON to a String using the Generic Map method in Salesforce Apex

            When we have to convert JSON to a string to create a more dynamic object, we can use a Map to handle the conversion.

            Follow the steps below to convert JSON to a string using the generic map method.

            In the Salesforce developer console, execute the anonymous window and write the code below.

            String jsonString = '{"name":"Alice","age":28}';
            Map<String, Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(jsonString);
            String serializedMap = JSON.serialize(jsonMap);
            System.debug(serializedMap);

            In the above code, we have used JSON.deserializeUntyped method to parse the JSON string and return a map of key-value pairs without specifying a particular object type.

            Then the JSON.serialize method converts the Map back into a JSON string.

            In the execution log window, the output would be displayed as a JSON string like the original, but it is converted to a String.

            Convert JSON to string using MAP method in Salesforce apex

            Following the above steps, we can convert JSON to a String in Salesforce Apex using the generic Map method.

            Conclusion

            In this Salesforce tutorial, we have learned the various approaches and methods to convert a JSON to a string in Salesforce Apex. By following the above steps, we successfully converted the apex to a string in Salesforce Apex using methods such as parse, deserialization, and mapping.

            By now, you will be able to convert the JSON data to a string in your Salesforce environment by following the above-explained methods.

            You may also like to read.

            Agentforce in Salesforce

            DOWNLOAD FREE AGENTFORCE EBOOK

            Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

            Salesforce flows complete guide

            FREE SALESFORCE FLOW EBOOK

            Learn how to work with flows in Salesforce with 5 different real time examples.