小编Aks*_*rma的帖子

Jackson 在序列化时不包含字段的类型信息

我正在尝试使用 jackson 2.6.3 将对象序列化为 json 我想在序列化的 json 中包含类型信息。这不适用于嵌套在此类中的成员。

这是测试代码。

public class Test {

@JsonSubTypes({ @JsonSubTypes.Type(value = ConcreteA.class)})
interface A {

}
@JsonTypeInfo( use=JsonTypeInfo.Id.CLASS)
class ConcreteA implements A {

}

@JsonSubTypes({ @JsonSubTypes.Type(value = ConcreteB.class)})
interface B {

}
@JsonTypeInfo( use=JsonTypeInfo.Id.CLASS)
class ConcreteB implements B {
    A a;
    public A getA() {
        return a=new ConcreteA();
    }
}

@org.junit.Test
public void testSerialisation() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    System.out.println(objectMapper.writeValueAsString(new ConcreteB()));
}
}
Run Code Online (Sandbox Code Playgroud)

jackson 正在转换的 json 是

{"@class":"Test$ConcreteB","a":{}}
Run Code Online (Sandbox Code Playgroud)

请注意,它不包括字段“a”的类型信息。仅序列化 A 时确实包含类型信息。 …

java json jackson fasterxml

1
推荐指数
1
解决办法
6503
查看次数

标签 统计

fasterxml ×1

jackson ×1

java ×1

json ×1