How can I serialize an object to JSON without properties that are null?

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/


This is old thread but it may help someone looking for out-of-box solution. Seems like Salesforce recently updated its API. Please try

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

I have tested it and it works.

serializePretty(objectToSerialize, suppressApexObjectNulls)

Suppresses null values when serializing Apex objects into JSON content and generates indented content using the pretty-print format.


Based on this JSON.Serialize method not returning null fields it looks like the behaviour is version dependent and that API version 25 (probably) strips out the nulls. I suggest you test with API versions from say 24 upwards and see what behaviour you get.

If you do find a version that strips out the nulls, set the class to that API version and add a large comment in your code that the API version is critical and why.

PS See georg w's comment - there is no version as far back as 25 that strips the nulls.

PPS If this is a one-off, then you can write your own serializer for this specific object using the JSONGenerator that includes the null checks.

Tags:

Json