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>
?
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;
}
}
对于没有 getter/setter 的解决方案,请确保像这样初始化something
:
public Optional<String> something = Optional.empty();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.