How can Jackson be configured to ignore a field value during serialization if that field\'s value is null.
For example:
public class SomeClass {
For Jackson 2.5 use :
@JsonInclude(content=Include.NON_NULL)
This has been troubling me for quite some time and I finally found the issue. The issue was due to a wrong import. Earlier I had been using
com.fasterxml.jackson.databind.annotation.JsonSerialize
Which had been deprecated. Just replace the import by
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
and use it as
@JsonSerialize(include=Inclusion.NON_NULL)
To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Alternatively, you could use @JsonInclude
in a getter so that the attribute would be shown if the value is not null.
A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.
If in Spring Boot, you can customize the jackson ObjectMapper
directly through property files.
Example application.yml
:
spring:
jackson:
default-property-inclusion: non_null # only include props if non-null
Possible values are:
always|non_null|non_absent|non_default|non_empty
More: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}
Global configuration if you use Spring
@Configuration
public class JsonConfigurations {
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
builder.failOnUnknownProperties(false);
return builder;
}
}