Java – Jackson Deserialize the missing attribute to null optional
•
Java
Suppose I have such a class:
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 the attribute is missing (in this case, just empty JSON), I get null instead of optional Of course I can initialize fields myself, but I think it's best to have a mechanism of null and missing attributes Is there any way to make Jackson deserialize the missing attribute empty and optional?
Solution
Optional is not really meant to be used as a field, but more as a return value Why not:
public static class Test {
private String something;
public Optional<String> getSomething() {
return Optional.ofNullable(something);
}
public void setSomething(String something) {
this.something = something;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
