java - JAXB/Jackson XML 通用序列化

标签 java xml jaxb jackson

我有一个 Shape类,和一个 CircleSquare子类。然后我有一个 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 注释 ShapeCircleSquare 才能工作:

@XmlRootElement
class Circle {
    //no-arg constructor
    Circle() {
    }
}

关于java - JAXB/Jackson XML 通用序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25032186/

相关文章:

java - 如何在 Java 中使用 GSON 将 JSON 对象的映射转换为 JSON?

android - 如何在Android中为圆形ImageView添加阴影效果?

java - 您如何自定义 JAXB 生成复数方法名称的方式?

java - CXF 的 JAXB 模式验证错误 - 发生 JAXBException : cvc-elt. 1:找不到元素的声明

xml - 使用 tokenize 函数分割文本

java - Xstream 或 Jaxb 架构支持

java - (Java 8) java.util.function.Supplier

java - 如何添加 Access 中的所有数据

java - 没有内核的 Libsvm

java - MarkLogic:没有可写入的流