Jackson 无法识别 @JsonCreator 注释
我目前正在使用 Jackson 1.4.2 并尝试反序列化从 UI 传递回 Java 控制器 (Servlet) 的 code
值(类型信息的唯一标识符)。
有多种类型(例如,ABCType
、XYZType
等)均从 AbstractType
扩展而来,但每种具体类型都有一个静态工厂方法它采用单个参数、唯一标识符,并返回由该标识符表示的类型对象(名称、关联类型、描述、有效首字母缩略词等)。每个具体类型(例如 XYZType
)中的静态方法都用 @JsonCreator
进行注释:
@JsonCreator
public static XYZType getInstance(String code) {
.....
}
我看到的问题是 Jackson 的映射器试图反序列化 json 时抛出的异常对于这些类型:
原因:org.codehaus.jackson.map.JsonMappingException:找不到类型[简单类型,类com.company.type.XYZtype]的默认构造函数:无法从Json对象实例化。
我在这里缺少静态工厂方法的 @JsonCreator
注释(或者它与 Jackson 1.4.2 与从 AbstractType
扩展的具体类型作斗争有关吗?) ?
I am currently using Jackson 1.4.2 and attempting deserialization of code
values (unique identifiers for type information) that are passed from our UI back to the Java controllers (Servlets).
There are multiple types (e.g. ABCType
, XYZType
, etc.) that all extend from an AbstractType
, but each concrete type has a static factory method that takes as a single parameter, a unique identifier, and returns the type object (name, associated types, description, valid acronyms, etc.) represented by that identifier. The static method within each concrete type (e.g. XYZType
) is annotated with @JsonCreator
:
@JsonCreator
public static XYZType getInstance(String code) {
.....
}
The problem that I am seeing though is an exception thrown by Jackson's mapper trying to deserialize the json to those types:
Caused by: org.codehaus.jackson.map.JsonMappingException: No default constructor found for type [simple type, class com.company.type.XYZtype]: can not instantiate from Json object.
What am I missing here of the @JsonCreator
annotation to static factory methods (or is it to do with Jackson 1.4.2 struggling with the concrete types extending from an AbstractType
?)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注解@JsonCreator需要注解@JsonProperty。此 Jackson wiki 页面 提供的信息很少,但提供了示例代码:
您可以在 这篇博文。
因此,您的示例代码应如下所示:
The annotation @JsonCreator requires the annotation @JsonProperty. This Jackson wiki page gives little information but does offer sample code:
You'll find a more detailed explanation at this blog post.
Your sample code should therefore look something like this:
问题是 Jackson 只看到声明的基类型,而不知道在哪里寻找子类型。
由于 1.5 中添加了完整的多态类型处理,因此您需要在 1.4 中做的是在基类中添加工厂方法并从那里添加调度方法。
Problem is that Jackson only sees the declared base type, and does not know where to look for subtypes.
Since full polymorphic type handling was added in 1.5, what you need to do with 1.4 is to add factory method in the base class and dispatch methods from there.