+ Start a Discussion

Removing null values in REST API response

I just wanted to remove the null values from the response, how can I achieve it?

For exmaple:
global class ResponseHandler {
    public String Status {get; set;}
    public List<sObject> result {get;set;}
    public String Message {get;set;}
    public String ErrorCode {get; set;}
global class OyeCodeRestAPI {
    global static ResponseHandler GET()
        ResponseHandler response = new ResponseHandler();
        Contact  returnContact = getContact();
            response.Status = 'Success';
            List<sObject> thesObjectList = new List<sObject>();
            response.Data = thesObjectList;
            response.ErrorCode = 'Error Code -0002';
            response.Status = 'error';
            response.Message = 'Fail : No Record Found';
        return response;

    public class NoRecordException extends Exception {}
    public static Contact getContact()
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String ContactId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); 
        Contact result;
            result = [SELECT Id, lastname, firstName, phone, email FROM Contact WHERE Id = :ContactId];
        Catch(System.QueryException e)
            throw new NoRecordException('Unable to find the record maching Id : '+ContactId);
        return result;

So on success, the response still has the Error Code & Message set to NULL. I just need to remove the same from the response to keep only what is required, how to achieve this?
Santiago CurettiSantiago Curetti
Helllo kpn,

Use the JSON.serialize method, and place the response in RestContext.response.responseBody
RestContext.response.responseBody = Blob.valueOf(JSON.serialize(response, true)); // true parameter suppresed null
and make your get method void
global static void GET()