简体   繁体   English

杰克逊继承和反序列化

[英]Jackson inheritance and deserialization

I am writing an API on top of Spring Web MVC/Spring Hateoas and even if the deserialization of simple class hierarchy works like a charm, I cannot manage to deserialize Json input to the proper type using jackson. 我正在Spring Web MVC / Spring Hateoas之上编写API,即使简单类层次结构的反序列化像魅力一样,我也无法使用jackson将Json输入反序列化为正确的类型。 Here is my class hierarchy : 这是我的类层次结构:

public class A {
    protected String fieldA;
}

public class B extends A {
    protected String fieldB;
}

public class C extends A {
    protected String fieldC;
}

Before everybody sends me to the many other similar questions on SO, the main difference here is that A is concrete . 在每个人向我发送关于SO的许多其他类似问题之前,这里的主要区别是A是具体的 In other words, Jackson has to choose between 3 implementations by using the json fields as tie breakers. 换句话说,杰克逊必须通过使用json字段作为断路器来选择3种实现方式。

Basically, how can I configure Jackson to have it deserialize : 基本上,我如何配置Jackson以使其反序列化:

{
    "fieldA": "asdf"
} 

to an instance of A, and 到A的实例,和

{
    "fieldA": "asdf",
    "fieldB": "asdf"
} 

to an instance of B ? 到B的一个例子?

There is no way to do that automatically: all automatic polymorphic type handling relies on type discriminator of some kind (type property, most commonly). 没有办法自动执行此操作:所有自动多态类型处理都依赖于某种类型的鉴别器(类型属性,最常见)。 Ability to use content-based heuristics has been requested, but so far no one has presented a viable plan (or contributions) for implementing functionality like this. 已经要求使用基于内容的启发式方法的能力,但到目前为止还没有人提出可行的计划(或贡献)来实现这样的功能。

To handle it you will probably need to write a custom JsonDeserializer and detect type yourself. 要处理它,您可能需要自己编写一个自定义JsonDeserializer并检测类型。 It might be possible to use ConvertingDeserializer , to let Jackson bind JSON into JsonNode or java.util.Map first, and then just extract it yourself. 也许可以使用ConvertingDeserializer ,让Jackson首先将JSON绑定到JsonNodejava.util.Map ,然后自己解压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM