[SalesForce] How to serialize an object to JSON without properties that are null

To communicate with a REST interface on a private system, I need to send a JSON message from a trigger. I have a message object that has some fields, lists and a child object:

public class MerchantConfig {

public class MIDConfig {
    public String mid;
    public String currencyCode;
    public String cardTemplateName;
    public String paymentPanelRestriction;
    public List<String> restrictedCountries; 
    public String paymentPanelRestrictionForCountries;
}

public String merchantName;
public String sopgTemplateName;
public Integer dispositionTimeWindowInMinutes;
public List<String> features;
public Boolean activateImmediately;
public List<MIDConfig> midConfiguration;
}

I can serialize it to JSON using the built-in serializer:

String body = JSON.serializePretty([MerchantConfig instance]);

The result:

{
  "sopgTemplateName" : null,
  "midConfiguration" : [ {
    "restrictionCountries" : [ "DE", "AT" ],
    "paymentPanelRestrictionForCountries" : "MANDATORY",
    "paymentPanelRestriction" : "OPTIONAL",
    "mid" : "1000000001",
    "currencyCode" : "EUR",
    "cardTemplateName" : null
  }, {
    "restrictionCountries" : [ ],
    "paymentPanelRestrictionForCountries" : "",
    "paymentPanelRestriction" : "OPTIONAL",
    "mid" : "1000000002",
    "currencyCode" : "USD",
    "cardTemplateName" : null
  }, {
    "restrictionCountries" : [ ],
    "paymentPanelRestrictionForCountries" : "",
    "paymentPanelRestriction" : "PROHIBITED",
    "mid" : "1000000003",
    "currencyCode" : "AUD",
    "cardTemplateName" : null
  } ],
  "merchantName" : "Test Merchant",
  "features" : [ XYZ ],
  "dispositionTimeWindowInMinutes" : 10,
  "activateImmediately" : true
}

How can I serialize this object so that all properties that are null don't show up in the JSON string?

In this example, "sopgTemplateName" and all "cardTemplateName" properties are null and should not appear in the JSON string. The empty list "restrictionCountries" should still appear as an empty list, though.

Best Answer

Depending on your use case, you might consider holding your state in a generic Map<String,Object> rather than in specific fields in an Apex class.

You can then use JSON.serialize(Map) which will simply omit the pseudo-fields that have not been added to the Map. Each Object in the Map could be a list or another map or a simple type.


foobarforce.com/.../apex-method-of-the-day-json-serialize-object/