Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jaxb - how to create XML from polymorphic classes

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?

like image 894
lukastymo Avatar asked Sep 21 '11 12:09

lukastymo


1 Answers

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

You can also leverage the xsi:type attribute as the inheritance indicator:

  • http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html

EclipseLink JAXB (MOXy) also has the @XmlDescriminatorNode/@XmlDescriminatorValue extension:

  • http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-moxy-extension.html
like image 195
bdoughan Avatar answered Sep 21 '22 00:09

bdoughan