4

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?

4
  • I don't believe that there is a way other than a custom serializer that you can use. Out the box JSON methods will take what they have an serialize it as is . With a custom serializer you will have the option of supplying a replacement for a null value.
    – Ronnie
    Apr 9, 2019 at 12:59
  • This method serialize(objectToSerialize, suppressApexObjectNulls) seems to work specifically on Apex Object types only and that the platform considers a Collection to be distinct from an Apex Object.
    – Jayant Das
    Apr 9, 2019 at 13:05
  • @JayantDas True. Same behaviour with List.
    – kvor
    Apr 9, 2019 at 13:08
  • @kvor Even though it does not clearly calls out, but going through few references it does establish this distinction, I have added details as answer, if that helps.
    – Jayant Das
    Apr 9, 2019 at 13:13

3 Answers 3

3

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:

8

Yep, that's the expected behavior.

For simple maps, you can get rid of null values by iterating over the map keys, keeping track of which ones have null values, and then a little map manipulation.

Set<String> mapKeysToRemoveSet = new Set<String>();

for(String key :myMap.keySet()){
    if(myMap.get(key) == null){
        mapKeysToRemoveSet.add(key);
    }
}

// The Map class only comes with a remove() method, which only removes one item from the
//   map at a time.
// It's not a great idea to modify a collection while you're iterating over it.
// The solution is to get the map's keyset, then use the set class's removeAll() method.
// This has the effect of removing multiple items from the map in one shot.
myMap.keySet().removeAll(mapKeysToRemoveSet);

System.debug(JSON.serialize(myMap));
1

This is a problem which I had faced, and I came across a string manipulation method that strips out nulls from null json keys.

  public static string stripJsonNulls(string JsonString)
{

    if(JsonString != null)
    {
        JsonString = JsonString.replaceAll('\"[^\"]*\":null',''); //basic removeal of null values
        JsonString = JsonString.replaceAll(',{2,}', ','); //remove duplicate/multiple commas
        JsonString = JsonString.replace('{,', '{'); //prevent opening brace from having a comma after it
        JsonString = JsonString.replace(',}', '}'); //prevent closing brace from having a comma before it
        JsonString = JsonString.replace('[,', '['); //prevent opening bracket from having a comma after it
        JsonString = JsonString.replace(',]', ']'); //prevent closing bracket from having a comma before it
    }

    return JsonString;
}


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

OP : {"key":"value"}

Src: https://iwritecrappycode.wordpress.com/2014/07/16/stripping-nulls-from-a-json-object-in-apex/

3
  • You want to trust a site called "I Write Crappy Code?"
    – corsiKa
    Apr 9, 2019 at 17:19
  • 😛 what's in the name ~ Shakespeare Apr 9, 2019 at 17:21
  • @PranayJaiswal Thanks but I would avoid using String.replaceAll(). It will result to "Regex too Complicated" Limit, if stripJsonNulls() is called in a loop.
    – kvor
    Jun 25, 2020 at 10:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .