How can Jackson be configured to ignore a field value during serialization if that field\'s value is null.
For example:
public class SomeClass {
You can use the following mapper configuration:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
Since 2.5 you can user:
mapper.setSerializationInclusion(Include.NON_NULL);
Jackson 2.x+ use
mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
This Will work in Spring boot 2.0.3+ and Jackson 2.0+
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
// your class variable and
// methods
}
Case one
@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;
Case two
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;
If someString
is null, it will be ignored on both of cases.
If someString
is "" it just only be ignored on case two.
The same for List = null
or List.size() = 0
If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
will result in:
[{myObject},null]
to get this:
[{myObject}]
one can do something like:
mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
throws IOException
{
//IGNORES NULL VALUES!
}
});
TIP: If you're using DropWizard you can retrieve the ObjectMapper
being used by Jersey using environment.getObjectMapper()
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
should work.
Include.NON_EMPTY
indicates that property is serialized if its value is not null and not empty.
Include.NON_NULL
indicates that property is serialized if its value is not null.