[SalesForce] to remove null value from the JSON response

I need help with sorting/cleaning up a json object. I have a global class for calling out responses with 4-5 objects.

Consider this example (for sample with 2 objects), My requirement is that I have to create account & list of contacts related to that account and an exception if anything breaks.
Respective responses should be sent for the above 3 objects as shown below, which is working fine. Main class & response are also working fine. Need some inputs for removing null objects from JSON.

response class:

global class Qc_Responses {

    global AccountResponse accountResponse {get;set;}
    global list<ContactResponse> contactResponses {get;set;}
    global ExceptionResponse exceptionResponse {get;set;}

    public class AccountResponse
    {
        public String statusCode;
        public String sfAccountId;
        public String message;

        // account Responses for Success / error 
        public AccountResponse(String statusCode, String accId){
            this.statusCode = statusCode;
            SFAccountId = accId;
            this.message = (String.isBlank(accId)) ? 'Account is not Created, Duplicate Account Found' : 'Account Created Successfully' ;
        }

    }

    public class ContactResponse{
        public String statusCode;
        public String message;
        public String sfContactid;
        public String email;
        public String lastName;
        public String phone;
        public ContactResponse(String statusCode,String message, String sfContactid, String email, String lastName, String phone){
            this.statusCode = statusCode;
            this.message = Message;  
            this.sfContactid = sfContactid;
            this.email = email;   
            this.phone = phone;
            this.lastName = lastName; 
        }
    }

    public class ExceptionResponse {
        public String message;
        public String errorCode;
        public ExceptionResponse(String message, String errorcode){
            this.message = message;
            this.errorCode = errorcode;
        }
    }   
}

json response :

{
    "exceptionResponse": null,
    "contactResponses": [
        {
            "statusCode": "201",
            "sfContactid": "0030k00000RpgLdAAJ",
            "phone": "+610212345678",
            "message": "1Contact(s) Created Successfully",
            "lastName": "Britto",
            "email": "sample1@salesforce.com"
        },
        {
            "statusCode": "201",
            "sfContactid": "0030k00000RpgLeAAJ",
            "phone": "+61-(02)-12346678",
            "message": "2Contact(s) Created Successfully",
            "lastName": "Smith",
            "email": "sample2@salesforce.com"
        }
    ],
    "accountResponse": {
        "statusCode": "201",
        "sfAccountId": "0010k00000PKwIpAAL",
        "message": "Account Created Successfully"
    }
}

Main Class :

( adding only the relevant code to minimize space )

@RestResource(urlMapping='/QACAcctServices/')
global with sharing class QAC_AccountServicesProcess 
{

    // Instance variables here

    @HttpPost
    global static QAC_Responses dosomeProcess()
    {
        // All Responses from Salesforce after processing
        QAC_Responses qacResp = new QAC_Responses();
        QAC_Responses.AccountResponse myAccResp;
        QAC_Responses.ContactResponse myContResp;
        QAC_Responses.ExceptionResponse myExcepResp;

        // some object responses are returned as lists after processing
        list<QAC_Responses.ContactResponse> myContRespList = new list<QAC_Responses.ContactResponse>();

        // local variables for business logic

        // Getting REST JSON from Request and setting to Response codes
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        receivedReq = req.requestBody.toString();

        try
        {
            system.debug(' @@ request 1 @@' +receivedReq);
            QAC_AccountServicesAPI acApi = QAC_AccountServicesAPI.parse(receivedReq);

                    QAC_AccountServicesAPI.AccountDetail accRecResp = acApi.agencyRegistration.accountDetail;

                        // insert Account records
                        createdAcc = doAccountCreation(accRecResp);
                        findObject = 'Account';
                        insert createdAcc;

                        if(createdAcc.Id != null)
                        {
                            res.statusCode = 201;
                            myAccResp = new QAC_Responses.AccountResponse('201', 
                                                                          accRecResp.referenceId,
                                                                          createdAcc.Id,
                                                                          accRecResp.iataCode,
                                                                          //accRecResp.tidsCode,
                                                                          accRecResp.AgencyABN);

                            qacResp.accountResponse = myAccResp;

                        }

                        // insert Contact (or) ACR Records
                        for(QAC_AccountServicesAPI.ContactDetails contRecResp : accRecResp.contactDetails)
                        {
                            // do some logics here and add .. 
                            newContactList.add(doContactCreation(contRecResp,createdAcc));
                        }
                        if(!newContactList.isEmpty())
                        {
                            findObject = 'Contact';
                            insert newContactList;
                            for(Contact eachContact : newContactList){
                                ++i;
                                if(eachContact.Id != null){
                                    res.statusCode = 201;
                                    myContResp = new QAC_Responses.contactResponse('201',i+'Contact(s) Created Successfully',
                                                                                   eachContact.Id,
                                                                                   eachContact.email,
                                                                                   eachContact.LastName,
                                                                                   eachContact.phone);
                                    myContRespList.add(myContResp);
                                }
                            }
                            i=0;
                            qacResp.contactResponses = myContRespList;
                        }
            system.debug('QAC Response**'+qacResp);
            return qacResp;
        }      
        catch(Exception ex)
        {
            isException = true;

            res.statusCode = 400;
            String sfErrMessage = ex.getMessage();

            if(ex.getMessage().contains(':')){
                sfErrMessage = ex.getMessage().split(':')[1];
            }

            if(ex.getTypeName().contains('JSON')){
                jsonErrMessage = 'Issue with JSON Format. Please check your Payload';
            }
            else{
                res.statusCode = (findObject == 'Account') ? 500 : 201 ;
                jsonErrMessage = 'Found errors, Registration Process Failed for - '+findObject+'.Please contact Salesforce';
            }

            myExcepResp = new QAC_Responses.ExceptionResponse('400',jsonErrMessage,
                                                              'Exception Found',sfErrMessage);
            qacResp.exceptionResponse = myExcepResp;

            system.debug('QAC Response**'+qacResp);
            return qacResp;
        }
    }
}

Need to do 2 things here in the response json..

  1. to remove the null value object here (if No Exception is found,
    to remove that part of exceptionResponse from JSON)
  2. to sort the
    response as account object first , then contact , then exception . .
    (to put accountResponse first in the JSON string and then remaining
    objects)

Please let me know if this can be done

Best Answer

Use the JSON.serialize method, and place the response in RestContext.response.responseBody, as follows:

RestContext.response.responseBody = Blob.valueOf(JSON.serialize(qacResp, true)); 
    // true = suppress nulls

You'll also need to change your return type from QAS_Responses to void:

global static void dosomeProcess()
Related Topic