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.
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?
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
}
You can also leverage the xsi:type
attribute as the inheritance indicator:
EclipseLink JAXB (MOXy) also has the @XmlDescriminatorNode
/@XmlDescriminatorValue
extension:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With