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.