Keep null values in Remote JSON call [closed]

I’m working with an external app that is making callouts to Remote Actions in my controller. When I return the value to them, it’s returning a custom data structure with 2 parameters, result, and error. When one of the parameters is null however, the JSON is dropping it altogether on the other side.

I saw the Apex JSON class has a suppress nulls parameter but that means the data structure would be returned as a String instead of this custom structure. The front end of this app is written in JS

Is there anyway to ensure the null value is retained?

global class Result{
   public Object result;
   public Object error;

   public Result(Object returnValue, CustomError methodError){
      this.result = returnValue;
      this.error = methodError;
   }
}

global class CustomError{
   public String code;

   public CustomError(String errorCode){
      this.code = errorCode;
   }
}

Value from Debug Log

Value from Chrome Dev Tools

Answer

Use the following code:

global static String doSomething() {
    ...
    return JSON.serialize(returnValue, false);
}

When you return a string, it won’t be jsonified, so the client will see the JSON as you meant it to be.

Attribution
Source : Link , Question Author : Adam Olshansky , Answer Author : sfdcfox

Leave a Comment