Jaxb - how to create XML from polymorphic classes

I just started using JAXB to output XML data from Java objects. Polymorphism exists in my Java classes that don't seem to work in JAXB.

Below is an example of how I tried to deal with this, but in the output I did not expect a 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 embarking on some complex inheritance development, is there a good approach to this?

+5
source share
2 answers

In your use case, you probably want to use @XmlElementRefs, this is consistent with the concept of permutation groups in an XML schema:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
    @XmlElement
    private String fieldInRoot;
    @XmlElementRef
    private BodyResponse child;
    // + getters and setters
}

xsi:type :

EclipseLink JAXB (MOXy) @XmlDescriminatorNode/@XmlDescriminatorValue:

+7
@XmlRootElement(name = "root")
public class Root {
    ....

    @XmlElements({
        @XmlElement(type = ResponseA.class, name = "ResponseA"),
        @XmlElement(type = ResponseB.class, name = "ResponseB")})
    private BodyResponse child;

}

, @XmlType(name = "ResponseX") Response.

+1

All Articles