1 year ago
#70009

Aethernite
Jackson deserializes absent optionals as nulls instead of Optional.empty()
Recently I've stumbled upon this problem:
Let's have an example java class that contains Optional property:
@Getter
@Setter
private static class DeserializingTestBean {
private String stringProperty;
private Optional<String> optionalStringProperty;
}
I've noticed that deserializing a json string to this object produces two different results depending on the json string:
CASE #1
{
"stringProperty": "test",
"optionalStringProperty": null
}
Using the Json String above we would get DeserializingTestBean object that will have stringProperty
set as test
and the optionalStringProperty
set as Optional.empty()
which is normal in this case. But let's check case 2.
CASE #2
{
"stringProperty": "test"
}
As you can notice the optional parameter is absent from this json string. When it creates the DeserializingTestBean object the optional parameter is set to null
which means we can get potential NPE if we call the .isPresent()
method.
There is a solution to this problem - we need to instantiate the Optional<String>
parameter to Optional.empty()
.
Is there an easier solution for a project where we have hundreds of such parameters that are not instantiated to Optional.empty()
?
I've considered the objectMapper.registerModule(new Jdk8Module().configureAbsentsAsNulls(true));
but it is not working. The method seems deprecated as well. Is there another configuration that I can use instead of instantiating every single Optional?
java
jackson
option-type
optional-parameters
jackson-databind
0 Answers
Your Answer