[SalesForce] Making “Null” as “” in JSON payload

I am trying to push a JSON input payload, but some fields might be blank.
The receiving system has a problem with it.
They want either the blank fields to not be sent all together or replace "Null" from JSON payload to "".
I was planning to do the latter…
I tried to use if-else condition to check if the field is blank and replace "Null" to "", but keep getting 500 Internal Error.

Incorrect Format ..

"displayName" : "Null",

Correct Format ..

"displayName" : "",

Does any one know how can this be done. The below code didn't work as callout failed with Internal Error , Status Code 500.

public static void postAccountToSystem(List<Id> acctIds){
Account acc = [SELECT Name,Display_Name__c,
                    FROM Account WHERE Id = :acctIds[0]];  

    if(acc.Display_Name__c == NULL){
        acc.Display_Name__c = '';

    if(acc.Bio_URL__c == NULL){
        acc.Bio_URL__c = '';
    if(acc.Image_URL__c == NULL){
        acc.Image_URL__c = '';

   String jsonInput = '{\n' +
        ' "displayName" : "'+acc.Display_Name__c+'",\n'+
        ' "bioUrl" : "'+acc.Bio_URL__c+'",\n'+
        ' "imageUrl" : "'+acc.Image_URL__c+'",\n'+
       System.enqueueJob(new QueueableCall(jsonInput, acc.Id));   

Best Answer

You should just serialize a Map<String, String>:

Map<String> data = new Map<String, String>
    'displayName' => acc.Display_Name__c,
    'bioUrl' => acc.Bio_URL__c,
    'imageUrl' => acc.Image_URL__c
String payload = JSON.serializePretty(data);
Related Topic