[SalesForce] JSON.serialize: is it possible to suppress null values of a map

I tried to serialize a map with null value (api 45):

Map<String, String> bodyMap = new Map<String, String> {'key'=>'value', 'key2'=>null};
System.debug(JSON.serialize(bodyMap,true));

but it does not suppress null value (as it does in a custom object):

{"key2":null,"key":"value"}

Does it work as expected? Is there any other way than writing custom serialiser?

Best Answer

The documentation for JSON.serialize(objectToSerialize, suppressApexObjectNulls) mentions the type of objectToSerialize parameter as:

Type: Object

The Apex object to serialize.

And if you refer to other documentations (mentioned below), a Collection is always categorized differently than an Apex Object. Apex Object always refers to instances of custom/system classes within the platform.

So the behavior what you are experiencing is expected. Your option is to either go with a custom class or serialize only after removing the null values from the collection.


References for data types in Apex which mentions Collection differently than Apex Objects: