In the Spring Boot 1.2.3, we can customize the Jackson ObjectMapper via properties file. But I didn't find a attribute can set Jackson ignore null value when serialization the Object to JSON string.
spring.jackson.deserialization.*= # see Jackson's DeserializationFeature spring.jackson.generator.*= # see Jackson's JsonGenerator.Feature spring.jackson.mapper.*= # see Jackson's MapperFeature spring.jackson.parser.*= # see Jackson's JsonParser.Feature spring.jackson.serialization.*=
I want to archive the same code like
ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL);
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!
Jackson default include null fields 1.2 By default, Jackson will include the null fields. To ignore the null fields, put @JsonInclude on class level or field level.
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.
Add the following line to your application.properties
file.
spring.jackson.default-property-inclusion=non_null
For versions of Jackson prior to 2.7:
spring.jackson.serialization-inclusion=non_null
This was a good solution before deprecation: @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
But now you should use:
@JsonInclude(JsonInclude.Include.NON_NULL) public class ClassName { ...
You can take a look here: https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html
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