Duplicated field in generated XML using JAXB

前端 未结 2 1129
遇见更好的自我
遇见更好的自我 2021-02-20 13:49

This is my scenario. I have a generic class:

public class Tuple extends ArrayList {
  //...
  public Tuple(T ...members) {
    this(Arrays.asLi         


        
2条回答
  •  遇见更好的自我
    2021-02-20 14:23

    You could use the following approach of marking the property @XmlTransient on the parent and @XmlElement on the child:

    Parent

    package forum7851052;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlTransient;
    
    @XmlRootElement
    public class Parent {
    
        private List item = new ArrayList();
    
        @XmlTransient
        public List getItem() {
            return item;
        }
    
        public void setItem(List item) {
            this.item = item;
        }
    
    }
    

    IntegerChild

    package forum7851052;
    
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class IntegerChild extends Parent {
    
        @Override
        @XmlElement
        public List getItem() {
            return super.getItem();
        }
    
        @Override
        public void setItem(List item) {
            super.setItem(item);
        }
    
    }
    

    StringChild

    package forum7851052;
    
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class StringChild extends Parent {
    
        @Override
        @XmlElement
        public List getItem() {
            return super.getItem();
        }
    
        @Override
        public void setItem(List item) {
            super.setItem(item);
        }
    
    }
    

    Demo

    package forum7851052;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Parent.class, IntegerChild.class, StringChild.class);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
            IntegerChild integerChild = new IntegerChild();
            integerChild.getItem().add(1);
            integerChild.getItem().add(2);
            marshaller.marshal(integerChild, System.out);
    
            StringChild stringChild = new StringChild();
            stringChild.getItem().add("A");
            stringChild.getItem().add("B");
            marshaller.marshal(stringChild, System.out);
        }
    
    }
    

    Output

    
    
        1
        2
    
    
    
        A
        B
    
    

提交回复
热议问题