JAXB - Unmarshalling polymorphic objects(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
这篇关于JAXB - 解组多态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JAXB - 解组多态对象


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01