我有2个这样的课程
class Parent {
private final Optional<Child> child;
@JsonCreator
Parent(@JsonProperty("child") Optional<Child> child) {
this.child = child;
}
}
class Child {
private final Optional<String> name;
@JsonCreator
Child(@JsonProperty("name")Optional<String> name){
this.name = name;
}
}
我打算反序列化到父类中的 json 如下所示:
{
"child" : {
"name" : "abc"
}
}
为了反序列化自身,我正在使用 ObjectMapper:
ObjectMapper mapper = new ObjectMapper()
.registerModule(new Jdk8Module());
但是在运行时出现以下异常:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.util.Optional` (no Creators, like default constructor, exist): cannot deserialize from Object value
堆栈上的很多答案建议使用
registerModule
,就像这样的one。我在使用 registerModule 时遗漏了什么吗?
我认为问题出在其他地方。可选值并不完全是作为类参数。它们应该用作方法返回值:
当然,人们会做他们想做的事。但我们在添加此功能时确实有一个明确的意图,它并不是为了成为通用的 Maybe 或 Some 类型,尽管很多人都希望我们这样做。我们的目的是为库方法返回类型提供一种有限的机制,其中需要有一种明确的方式来表示“无结果”,而使用 null 极有可能会导致错误。 这里的关键是关注用作返回类型。
来源:https://blog.joda.org/2014/11/optional-in-java-se-8.html
所以我认为你应该专注于序列化/反序列化空值,并仅使用可选值作为 getter 的返回值,如下所示:
class Parent {
private final Child child;
@JsonCreator
Parent(Child child) {
this.child = child;
}
Optional<Child> getChild() {
return Optional.ofNullable(child);
}
}
class Child {
private final String name;
@JsonCreator
Child(String name){
this.name = name;
}
Optional<String> getName() {
return Optional.ofNullable(name);
}
}