5

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

  • At first glance this question seems to be a duplicate of How to JSON.serialize not including null values (just the converse). Can you share the code you are actually using to serialize? Seems like you may have accidentally just serialized a second time when changing the signature? – Adrian Larson Jul 14 '17 at 5:20
0

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.

  • I tried doing that but it ended up returning in the form of a string with a bunch of escape characters, instead of a data structure. In the format "{\"result\":"a0zn0000001ZC5yAAG",\"error\":null}" or something like that, that would then need to be deserialized. Is there any way for it to return a data structure/Object instead of a string? – Adam Olshansky Jul 14 '17 at 3:21
  • @AdamOlshansky Visualforce remoting automatically protects you by default, so you have to request that it not do so. Change your client to call it with the options parameter set to "escape: false", like this: controllerName.methodName(function(result, event) { ... }, { escape: false }) – sfdcfox Jul 14 '17 at 12:22
  • Confirmed that we're doing that as well already but still no luck – Adam Olshansky Jul 14 '17 at 16:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.