6

We are using ObjectMapper to ignore serialisation of null maps in our project

configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)

But after Jackson-Databind 2.9, the property is depreciated and we are looking for an alternate option.

Can the below code work as substitute for removing the above property -

setSerializationInclusion(Include.NON_NULL)
Abhinav Jain
  • 110
  • 1
  • 5

1 Answers1

9

From documentation:

Deprecated. Since 2.9 there are better mechanism for specifying filtering; specifically using JsonInclude or configuration overrides (see ObjectMapper.configOverride(Class)). Feature that determines whether Map entries with null values are to be serialized (true) or not (false).
NOTE: unlike other SerializationFeatures, this feature cannot be dynamically changed on per-call basis, because its effect is considered during construction of serializers and property handlers.

Feature is enabled by default.

Simple example:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Value;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.HashMap;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("string", "value");
        map.put("int", 1);
        map.put("null1", null);
        map.put(null, null);

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.configOverride(Map.class).setInclude(Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));

        System.out.println(mapper.writeValueAsString(map));
    }
}

Above code prints:

{
  "string" : "value",
  "int" : 1
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    I see that this alteration works, but don't really understand the reason for the deprecation. Can anyone give a more explicit/usefull description for the deprecation? – Bill Naylor Mar 06 '23 at 20:13
  • 1
    Have to admit I also found the javadocs for `setInclude` rather opaque. – Bill Naylor Mar 06 '23 at 20:24
  • @BillNaylor, added [note](https://fasterxml.github.io/jackson-databind/javadoc/2.13/com/fasterxml/jackson/databind/SerializationFeature.html#WRITE_NULL_MAP_VALUES) should give you better reason why: `unlike other SerializationFeatures, this feature cannot be dynamically changed on per-call basis, because its effect is considered during construction of serializers and property handlers.` – Michał Ziober Mar 06 '23 at 22:06