Explain Codes LogoExplain Codes Logo

How to tell Jackson to ignore a field during serialization if its value is null?

java
json-serialization
objectmapper
custom-serializer
Anton ShumikhinbyAnton Shumikhin·Jul 22, 2024
TLDR

Simply use the @JsonInclude(JsonInclude.Include.NON_NULL) annotation at the field or class level for Jackson to ignore null fields during serialization.

@JsonInclude(JsonInclude.Include.NON_NULL) public class MyClass { private String nonNullField; private String nullableField; // Sneaky: Will vanish if null during serialization }

This ensures your JSON output is clean and lean, having only non-null fields.

Ignore nulls across the whole application

If you are a fan of consistency and want to ignore nulls across all your data models, simply configure your ObjectMapper like this:

ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // It's a once in a lifetime kind of thing now.

This kung-fu move configures Jackson to consistently ignore null fields globally, wherever the ObjectMapper is used.

Exclude nulls selectively on getters

In some cases, you might want to exercise more control and select which fields to ignore when their value is null. Here, using the annotation on getter methods comes to the rescue:

public class SelectiveSerialization { private String alwaysSerialized; private String conditionalNull; // This champ is always serialized, whether null or not. @JsonInclude(JsonInclude.Include.ALWAYS) public String getAlwaysSerialized() { return alwaysSerialized; } // This lad only shows up if not null. @JsonInclude(JsonInclude.Include.NON_NULL) public String getConditionalNull(){ return conditionalNull; } }

By this way, you add some flavor to the output, making some fields essential to serialization, and ignoring others when null.

Advanced techniques: legacy and anniversaries

While dealing with legacy systems, you may come across versions of Jackson pre-dating the 2.x era. For Jackson 1.x, the syntax differs slightly: @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL).

Also, remember that data likes parties too! Overusing null exclusions might lead to data feeling left out, causing data loss or distortion. Employ these techniques understanding your application's needs.

Mixing nulls and collections

Ever thought of how to deal with Collections and Maps containing null values? Here's a neat trick:

@JsonInclude(JsonInclude.Include.NON_NULL) public class NullTolerantMap { private Map<String, Object> items = new HashMap<>(); @JsonAnyGetter public Map<String, Object> getItems() { return items.entrySet().stream() .filter(entry -> entry.getValue() != null) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } } // This map is so neat, it only displays items, nulls are invisible!

This practice helps in yielding cleaner JSON output when dealing with complex structures like Maps.

Picasso-ing nulls: Crafting custom serializers

When common practice is not enough, and you feel a little Picasso-ish, try crafting a custom serializer for complex serialization control:

public class NullSkippingSerializer extends JsonSerializer<Object> { @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (value != null) { gen.writeObject(value); } // Null values are like John Cena here, you can't see them! } } // Use the Picasso masterpiece with @JsonSerialize @JsonSerialize(using = NullSkippingSerializer.class) private String customField;

It's a bit of an overkill sometimes, but where complexity demands, custom solutions shine best!

Bypassing potential Bombs (gotchas!)

Always remember: omitting nulls should not become an Optimus Prime in disguise (Transformers, get it?!?). Misusing this technique might lead to data corruption or misinterpreted state. So, advise API clients about potential absence of certain fields due to null value exclusion.