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
How to Get the Current Date and Time in Utc or Gmt in Java
How to Find a Button Source in Awt (Calculator Homework)
Maven: Add a Dependency to a Jar by Relative Path
Close a Scanner Linked to System.In
Difference Between a Static and a Non-Static Initialization Code Block
Difference Between Final and Effectively Final
"Expected Begin_Object But Was String At Line 1 Column 1"
How to Assert That a Certain Exception Is Thrown in Junit Tests
Standard Concise Way to Copy a File in Java
Java.Net.Connectexception: Connection Refused
How to Parse Command Line Arguments in Java