JAXB - 解组多态对象

2022-01-19 00:00:00 java jaxb

我得到的 XML 看起来像(当然还有更多属性):

I'm given XML that looks like (lots more attributes of course):

<inventory>
  <item kind="GRILL" tag=123 brand="WEBER"/>
  <item kind="CAR" tag=124 make="FORD" model="EXPLORER" />
</inventory>

大约有十几种不同的种类.我正在使用注释映射到如下所示的 java 类:

with about a dozen different kinds. I am using annotations to map to java classes that look like:

@XmlRootElement(name="inventory")
public class Inventory {
  @XmlElement(name="item")
  public List<Item> itemList = new LinkedList<Item>;
}
abstract public class Item {
  @XmlAttribute public int tag;
}
public class Grill extends Item {
  @XmlAttribute public string brand;
}
public class Car extends Item {
  @XmlAttribute public string make;
  @XmlAttribute public string model;
}

如何让 JAXB 根​​据种类"字段创建子类 Item 对象?

How can I get JAXB to create the sub-classed Item objects based on the "kind" field?

推荐答案

有几种不同的方法:

JAXB (JSR-222)

以下方法适用于任何 JAXB 实现(Metro、MOXy、JaxMe 等).使用 XmlAdapter,其中适配对象包含父类和所有子类的属性.在 XmlAdapter 中添加何时应使用特定子类的逻辑.有关示例,请参见下面类似问题的链接:

The following approach should work with any JAXB implementation (Metro, MOXy, JaxMe, etc). Use an XmlAdapter where the adapted object contains the properties of the parent class and all the subclasses. In the XmlAdapter add the logic of when a particular subclass should be used. For an example see the link to a similar question below:

  • Java/JAXB:解组特定 Java 对象属性的 XML 属性

EclipseLink JAXB (MOXy)

您可以使用 EclipseLink JAXB (MOXy) 中的 @XmlDecriminatorNode 扩展来处理这个用例.

You could use the @XmlDescriminatorNode extension in EclipseLink JAXB (MOXy) to handle this use case.

查看我对类似问题的回答:

Check out my answer to a similar question:

  • Java/JAXB: 根据属性将 Xml 解组到特定的子类

我们在 EclipseLink 2.2 版本中改进了这种支持:

We improved this support in the EclipseLink 2.2 release:

  • http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-moxy-extension.html

相关文章