Jackson Faster XML:如何解析抽象类'孩子?混入?

问题描述 投票:1回答:2

我们通过xcj使用模式生成的对象类型。因此,对类型的定义不是非常灵活的控制。我们还使用JAXB注释。

然后,我们使用Jackson Faster XML对这些对象进行反序列化。不幸的是,当我们反序列化抽象类时,我们得到一个例外:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of 
com.x.y.z.AnstractType: abstract types either need to be mapped to concrete types, 
have custom deserializer, or contain additional type information at 
[Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@2989b3db; 
line: 1, column: 625] (through reference chain: com.x.y.z.TypeA["type-b-prop"]->
com.x.y.z.TypeB["type-c-prop"]->java.util.ArrayList[0]->
com.x.y.z.TypeC["abstract-type-prop"]->java.util.ArrayList[0])

通过添加mixin,可以轻松地为抽象类的单个子项解决上述问题:

@JsonTypeInfo(defaultImpl = ChildType.class, use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
static class AbstractTypeMixIn {
}

并在对象映射器中注册它:

objectMapper = new ObjectMapper();
objectMapper.addMixIn(AbstractType.class, AbstractTypeMixIn.class);
...
objectMapper.registerModule(new JaxbAnnotationModule());    

当单个类继承抽象类时,这就像一个魅力。多个孩子怎么样?知道如何为抽象类的多个继承者实现它吗?如果不是mixins,还有什么?

java xml jackson fasterxml
2个回答
1
投票

问题是我只使用mixin来解析响应,而不是写它。因此,解决方案是使用相同的mixins作为对象映射器进行序列化和反序列化。以下定义就足够了:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
static class AbstractTypeMixIn {
}

它只是在JSON中为不明确的子类添加@type属性。


0
投票

@JsonSubTypes注释可能对您有用。有关详细信息,请参阅Is Jackson's @JsonSubTypes still necessary for polymorphic deserialization?

© www.soinside.com 2019 - 2024. All rights reserved.