Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ignore empty Optional field during Jackson Serialization

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading