JAXB: how to unmarshal a List of objects of different types but with common parent?

前端 未结 3 1326
误落风尘
误落风尘 2020-12-09 19:01

There is a fairly common pattern in our applications. We configure a configure a set (or list) of objects in Xml, which all implement a common interface. On start-up, the

3条回答
  •  悲&欢浪女
    2020-12-09 19:14

    Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

    If you are using MOXy as your JAXB provider then you could use the MOXy's @XmlPaths annotation to extend the standard JAXB @XmlElements annotation to do the following:

    Fees

    import java.util.List;
    import javax.xml.bind.annotation.*;
    import org.eclipse.persistence.oxm.annotations.*;
    
    @XmlRootElement
    public class Fees {
    
        @XmlElements({
            @XmlElement(type=Commission.class),
            @XmlElement(type=FINRAPerShare.class),
            @XmlElement(type=SEC.class),
            @XmlElement(type=Route.class)
        })
        @XmlPaths({
            @XmlPath("fee[@type='Commission']"),
            @XmlPath("fee[@type='FINRAPerShare']"),
            @XmlPath("fee[@type='SEC']"),
            @XmlPath("fee[@type='Route']")
        })
        private List fees;
    
    }
    

    Commission

    The implementations of the Fee interface would be annotated normally.

    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Commission implements Fee {
    
        @XmlAttribute
        private String name;
    
        @XmlAttribute
        private String rate;
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
    • http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html
    • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

提交回复
热议问题