jaxb-如何从多态类创建XML [英] jaxb - how to create XML from polymorphic classes
问题描述
我刚刚开始使用JAXB从Java对象生成XML输出.我的java类中存在一种多态性,这在JAXB中似乎不起作用.
I've just started using JAXB to make XML output from java objects. A polymorphism exists in my java classes, which seems to not working in JAXB.
下面是我尝试处理它的方式,但是在输出中我没有期望的字段:fieldA或fieldB.
Below is the way how I tried to deal with it, but in the output I haven't expected field: fieldA or fieldB.
@XmlRootElement(name = "root")
public class Root {
@XmlElement(name = "fieldInRoot")
private String fieldInRoot;
@XmlElement(name = "child")
private BodyResponse child;
// + getters and setters
}
public abstract class BodyResponse {
}
@XmlRootElement(name = "ResponseA")
public class ResponseA extends BodyResponse {
@XmlElement(name = "fieldA")
String fieldB;
// + getters and setters
}
@XmlRootElement(name = "ResponseB")
public class ResponseB extends BodyResponse {
@XmlElement(name = "fieldB")
String fieldB;
// + getters and setters
}
在我开始发明一些复杂的继承之前,有什么好的方法可以做到这一点?
Before I start invent some intricate inheritances, is there any good approach to do this?
推荐答案
对于您的用例,您可能想利用@XmlElementRefs
,它对应于XML Schema中的替换组的概念:
For your use case you will probably want to leverage @XmlElementRefs
, this corresponds to the concept of substitution groups in XML Schema:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement
private String fieldInRoot;
@XmlElementRef
private BodyResponse child;
// + getters and setters
}
- http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
- http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
您还可以将xsi:type
属性用作继承指标:
You can also leverage the xsi:type
attribute as the inheritance indicator:
EclipseLink JAXB(MOXy)也具有@XmlDescriminatorNode
/@XmlDescriminatorValue
扩展名:
EclipseLink JAXB (MOXy) also has the @XmlDescriminatorNode
/@XmlDescriminatorValue
extension:
这篇关于jaxb-如何从多态类创建XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!