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

查看:176
本文介绍了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: Unmarshall XML attributes to specific Java object attributes

EclipseLink JAXB(MOXy)

您可以在@XmlDescriminatorNode扩展名中使用 EclipseLink JAXB(MOXy)来处理此用例。

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: Unmarshall Xml to specific subclass based on an attribute

我们在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

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

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