【发布时间】:2015-04-10 20:45:06
【问题描述】:
我有以下带有 Jaxb 注释的类层次结构,包括在文档根元素处的继承:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ParentClass", propOrder = {
"parentField"
})
public class ParentClass{
@XmlElement(name = "ParentField")
protected String parentField;
getters and setters here
}
ChildAClass:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ChildAClass", propOrder = {
"childAfield"
})
public class ChildAClass extends ParentClass{
@XmlElement(name = "ChildAfield")
protected String childAfield;
getters and setters here
}
ChildB类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ChildBClass", propOrder = {
"childBfield"
})
public class ChildBClass extends ParentClass{
@XmlElement(name = "ChildBfield")
protected String childBfield;
getters and setters here
}
这是非常简单的类层次结构。比我有简单的测试,我序列化 ChildAClass 并尝试反序列化为 ParentClass。我希望propper类被反序列化并向上转换为ParentClass。我想这是一个有效的用例。
序列化文档如下,这里没什么特别的。
{
"ChildAfield": "child A field",
"ParentField": "parent from child A"
}
但是当我尝试反序列化时:
mapper = new ObjectMapper();
JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
mapper.registerModule(jaxbAnnotationModule);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_
ParentClass parentClass = mapper.readValue(new File(PATH_TO_FILE), ParentClass.class);
我收到以下异常:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ChildAfield" (class inheritance.model.ParentClass), not marked as ignorable (one known property: "ParentField"])
at [Source: src/test/resources/testfiles/json/inheritance.json; line: 2, column: 19] (through reference chain: inheritance.model.ParentClass["ChildAfield"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty( ...
我想这里缺少一些类型元数据,用于适当的类型推断和反序列化。我一直在寻找@JsonTypeInfo,但我仅限于 JAXB。我尝试了@XmlElements jaxb 注释,但无法使其工作。
谁能给个提示?
谢谢
【问题讨论】:
标签: java json serialization jaxb jackson