我有一个 Shape
类,和一个 Circle
和 Square
子类。然后我有一个 Container
具有 List<Shape> shapes
的类字段。
我正在使用 Jackson 进行 XML 序列化,我得到了
<shapes><shape radius=".."><shape w=".." h=".."></shapes>
...但我真正想要的是
<shapes><circle radius=".."><square w=".." h=".."></shapes>
我试过注释 shapes
与
@XmlElements({
@XmlElement(type = Circle.class),
@XmlElement(type = Square.class)
})
...但这只是给了我
<shapes><shapes><Circle radius=".."></shapes><shapes><Square w=".." h=".."></shapes></shapes>
...所以它几乎是正确的,但是那些包装器很烦人。有什么方法可以得到我想要的东西,即使这意味着更改我的 JAXB 实现?
最佳答案
其中一个选项是使用 @XmlElementRef注解。 javadoc 摘录:
This annotation dynamically associates an XML element name with the JavaBean property. When a JavaBean property is annotated with XmlElement, the XML element name is statically derived from the JavaBean property name. However, when this annotation is used, the XML element name is derived from the instance of the type of the JavaBean property at runtime.
所以,你可以这样做:
@XmlRootElement
class Container {
//...
//without XmlElementWrapper <shapes> element will be omitted
@XmlElementWrapper(name="shapes")
@XmlElementRef
public List<Shape> getShape() {
//your logic here
}
}
检查 javadoc 中的约束。您可能需要使用 @XmlRootElement
注释 Shape
、Circle
和 Square
才能工作:
@XmlRootElement
class Circle {
//no-arg constructor
Circle() {
}
}
关于java - JAXB/Jackson XML 通用序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25032186/