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

前端 未结 3 1320
误落风尘
误落风尘 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:30

    You could use an XmlAdapter for this use case. The impl bleow handles just the Commission type but could be easily extended to support all the types. You need to ensure that AdaptedFee contains the combined properties from all the implementations of the Fee interface.

    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class FeeAdapter extends XmlAdapter{
    
        public static class AdaptedFee {
    
            @XmlAttribute
            public String type;
    
            @XmlAttribute
            public String name;
    
            @XmlAttribute
            public String rate;
    
        }
    
        @Override
        public AdaptedFee marshal(Fee fee) throws Exception {
            AdaptedFee adaptedFee = new AdaptedFee();
            if(fee instanceof Commission) {
                Commission commission = (Commission) fee;
                adaptedFee.type = "Commission";
                adaptedFee.name = commission.name;
                adaptedFee.rate = commission.rate;
            }
            return adaptedFee;
        }
    
        @Override
        public Fee unmarshal(AdaptedFee adaptedFee) throws Exception {
            if("Commission".equals(adaptedFee.type)) {
                Commission commission = new Commission();
                commission.name = adaptedFee.name;
                commission.rate = adaptedFee.rate;
                return commission;
            }
            return null;
        }
    
    }
    

    An XmlAdapter is configured using the @XmlJavaTypeAdapter annotation:

    import java.util.List;
    import javax.xml.bind.annotation.*;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Fees {
    
        @XmlElement(name="fee")
        @XmlJavaTypeAdapter(FeeAdapter.class)
        private List fees;
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2012/01/jaxb-and-inhertiance-using-xmladapter.html

提交回复
热议问题