How to Tell Jackson to Ignore a Field During Serialization If Its Value Is Null

How to tell Jackson to ignore a field during serialization if its value is 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.

Jackson serialization: ignore empty values (or null)

You have the annotation in the wrong place - it needs to be on the class, not the field. i.e:

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
public static class Request {
// ...
}

As noted in comments, in versions below 2.x the syntax for this annotation is:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY

The other option is to configure the ObjectMapper directly, simply by calling
mapper.setSerializationInclusion(Include.NON_NULL);

(for the record, I think the popularity of this answer is an indication that this annotation should be applicable on a field-by-field basis, @fasterxml)

Jackson serialization - ignore not set values but provide values explicitly set to null

This can be achieved using Optional fields:

public class JsonTest {
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
static class Example {
private Optional<String> name;
private Optional<String> test;
}

public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());

Example[] examples = {
new Example(),
Example.builder().name(Optional.of("exampleName")).build(),
Example.builder().name(Optional.of("exampleName")).test(Optional.empty()).build(),
};

for (Example ex : examples) {
System.out.println(mapper.writeValueAsString(ex));
}
}
}

Output:

{}
{"name":"exampleName"}
{"name":"exampleName","test":null}


Related Topics



Leave a reply



Submit