jaxb - how to create XML from polymorphic classes

瘦欲@ 提交于 2021-02-07 03:19:15

问题


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?


回答1:


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



回答2:


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

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

}

Maybe you need an @XmlType(name = "ResponseX") on your Response classes.



来源:https://stackoverflow.com/questions/7499735/jaxb-how-to-create-xml-from-polymorphic-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!