Given the following class:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Account {
[... A lot of serialized properties]
@JsonSerialize(nullsUsing = JacksonSpringSpelSerializer.class, using = JacksonSpringSpelSerializer.class)
@JsonView(View.Contract.class)
@Value("#{@contractService.getActiveContract(#this)}")
public Contract activeContract;
}
Basically the property activeContract
is null, and its value is evaluated only when the correct @JsonView is provided, the value is computed by a Spring Spel expression, everything is done in a custom Serializer JacksonSpringSpelSerializer
.
Everything works as expected BUT the computed value can sometimes be null, which is normal, and I end up with a json like this:
{
[... All properties],
"activeContract": null
}
The issue is that I don't want null properties to be in the returned json, the @JsonInclude(JsonInclude.Include.NON_EMPTY)
is ignored when a custom serializer is set on a property.
After digging a bit, I found out that the custom serializer is called by BeanPropertyWriter.serializeAsField()
that contains:
if (value == null) {
if (_nullSerializer != null) {
gen.writeFieldName(_name);
_nullSerializer.serialize(null, gen, prov);
}
return;
}
So the name of the field is written by gen.writeFieldName(_name);
before the custom serializer is actually called, and I didn't find a proper way to prevent this behavior or to remove the null properties generated by the custom Serializer.
Is there a proper way to achieve such a result ? Any advice would be very welcome :D
Thanks <3