JAXB - 解组多态对象 [英] JAXB - Unmarshalling polymorphic objects

查看:36
本文介绍了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:

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:

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

We improved this support in the EclipseLink 2.2 release:

这篇关于JAXB - 解组多态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆