Reputation: 1771
Let's say I have a class like this:
public static class Test {
private Optional<String> something;
public Optional<String> getSomething() {
return something;
}
public void setSomething(Optional<String> something) {
this.something = something;
}
}
If I deserialize this JSON, I get an empty Optional:
{"something":null}
But if property is missing (in this case just empty JSON), I get null instead of Optional<T>
. I could initialize fields by myself of course, but I think it would be better to have one mechanism for null
and missing properties. So is there a way to make jackson deserialize missing properties as empty Optional<T>
?
Upvotes: 9
Views: 5339
Reputation: 4069
For a solution without getters/setters, make sure something
get initialized like this:
public Optional<String> something = Optional.empty();
Upvotes: 6
Reputation: 328598
Optional is not really meant to be used as a field but more as a return value. Why not have:
public static class Test {
private String something;
public Optional<String> getSomething() {
return Optional.ofNullable(something);
}
public void setSomething(String something) {
this.something = something;
}
}
Upvotes: 3