I normally use objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL) because I never want the null values of my classes serialized. Except now I have a specific field should be written out, even if it is null. Is there a quick annotation I can put on this one field that overrides the Inclusion.NON_NULL property for that one field? What's a good way to achieve this?
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
Include. NON_NULL: Indicates that only properties with not null values will be included in JSON. Include. NON_EMPTY: Indicates that only properties that are not empty will be included in JSON. Non-empty can have different meaning for different objects such as List with size zero will be considered as empty.
An object that converts between JSON and the equivalent Foundation objects. iOS 5.0+ iPadOS 5.0+ macOS 10.7+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+
@JsonInclude It says that if the value of a property (or all properties) in question is equal to a certain value ( null , empty - whatever that means, or a default value) this property is not serialized. Without this annotation, the property value is always serialized.
With Jackson 1.x you can use @JsonSerialize(include = Inclusion.ALWAYS)
and with Jackson 2.x you can use @JsonInclude(Include.ALWAYS)
. These annotations will override the default config from your ObjectMapper
.
@user1433372, JsonInclude is an annotation only for Jackson 2.x.
in Jackson 1.9
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
is the same in Jackson 2.x as
@JsonInclude(JsonInclude.Include.NON_EMPTY)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With