Bartosz Bilicki Bartosz Bilicki - 18 days ago 9
Java Question

How to make Immutables library skip serializing Optional fields

I am working with Immutables library (https://immutables.github.io). I need my classes to serialize to JSON (I use Jackson). I want to skip Optional fields in my output JSON. Before Immutables, I provided

@JsonInclude(JsonInclude.Include.NON_EMPTY)
at class level.

It seems, Immutables is not respecting that annotation.
If I annotate every Optional field with
@JsonInclude(JsonInclude.Include.NON_EMPTY)
it works fine.

Is it possible to instruct Immutables to skip serializing empty Optionals using class-level (not field-level) annotation? I see
org.immutables.value.Value.Style#additionalJsonAnnotations
but there is no customize passed annotation using it.

I have jackson-datatype-jdk8 in my classpath, and my
com.fasterxml.jackson.databind.ObjectMapper
has


mapper.registerModule(new
Jdk8Module().configureAbsentsAsNulls(true));

Answer

Issue is resolved in Immutables since version v2.3.6 (possibly earlier). Immutables is respecting @JsonInclude, @JsonPropertyOrder and other class-level (or field-level) annotations from Jackson. Those annotations are copied to generated Immutable class and they work as expected.