I want to ignore an Optional field value during serialization if its value is null.
Employee.java
class Employee {
private String firstName;
private String secondName;
public Optional<String> getFirstName() {
return Optional.ofNullable(firstName);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Optional<String> getSecondName() {
return Optional.ofNullable(secondName);
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
}
have configured Jackson as below:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println(objectMapper.writeValueAsString(employee));
The serialization method is giving below output:
{"firstName":"foo", "secondName":null}
But we want result like below:
{"firstName":"foo"}
>Solution :
The javadoc for Optional states:
Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors.
In other words, you shouldn’t be using Optional here in the first place.
However, if you still want to, @JsonInclude(NON_ABSENT) (doc) should work just fine.