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