@JsonTypeInfo和多个继承级别

时间:2018-10-11 07:51:41

标签: jackson2

使用杰克逊2.9.6,我遇到了以下问题,对我来说,这看起来像是个错误。抽象超类A具有两个子类B和C,其中B再次具有子类D

添加 @JsonTypeInfo @JsonSubTypes 注释,如下所示,我希望B,C和D都应使用 type = name序列化discriminator 字段,但看起来“ B”位于对象层次结构的“中间”,而是使用简单的类名作为类型值进行序列化。

@JsonTypeInfo(use = NAME, include = PROPERTY, property = "type")
@JsonSubTypes({
        @Type(value = B.class, name = "nameB"),
        @Type(value = C.class, name = "nameC"),

})
abstract class A {
    private final int i;

    public int getI() {
        return i;
    }

    public A(int i) {
        this.i = i;
    }

}

@JsonTypeInfo(use = NAME, include = PROPERTY, property = "type")
@JsonSubTypes({
        @Type(value = D.class, name = "nameD"),

})
class B extends A {

    public B(int i) {
        super(i);
    }

}

class C extends A {

    public C(int i) {
        super(i);
    }

}

class D extends B {

    public D(int i) {
        super(i);
    }

}

使用以下测试进行复制:

@Test
public void testA() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new B(42)));
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new C(42)));
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new D(42)));

} 

产生:

{
  "type" : "B",
  "i" : 42
}
{
  "type" : "nameC",
  "i" : 42
}
{
  "type" : "nameD",
  "i" : 42
}

0 个答案:

没有答案