How to tell Jackson to ignore a field during serialization if its value is null?
Simply use the @JsonInclude(JsonInclude.Include.NON_NULL)
annotation at the field or class level for Jackson to ignore null fields 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:
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:
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:
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:
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.
Was this article helpful?