I can't understand why this JAXB IllegalAnnotationException is thrown

后端 未结 12 1775
渐次进展
渐次进展 2020-12-13 02:03

This is my XML file:


    
    
    
                   


        
12条回答
  •  渐次进展
    2020-12-13 02:35

    The exception is due to your JAXB (JSR-222) implementation believing that there are two things mapped with the same name (a field and a property). There are a couple of options for your use case:

    OPTION #1 - Annotate the Field with @XmlAccessorType(XmlAccessType.FIELD)

    If you want to annotation the field then you should specify @XmlAccessorType(XmlAccessType.FIELD)

    Fields.java:

    package forum10795793;
    
    import java.util.*;
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement(name = "fields")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Fields {
    
        @XmlElement(name = "field")
        List fields = new ArrayList();
    
        public List getFields() {
            return fields;
        }
    
        public void setFields(List fields) {
            this.fields = fields;
        }
    
    }
    

    Field.java:

    package forum10795793;
    
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Field {
    
        @XmlAttribute(name = "mappedField")
        String mappedField;
    
        public String getMappedField() {
            return mappedField;
        }
    
        public void setMappedField(String mappedField) {
            this.mappedField = mappedField;
        }
    
    }
    

    OPTION #2 - Annotate the Properties

    The default accessor type is XmlAccessType.PUBLIC. This means that by default JAXB implementations will map public fields and accessors to XML. Using the default setting you should annotate the public accessors where you want to override the default mapping behaviour.

    Fields.java:

    package forum10795793;
    
    import java.util.*;
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement(name = "fields")
    public class Fields {
    
        List fields = new ArrayList();
    
        @XmlElement(name = "field")
        public List getFields() {
            return fields;
        }
    
        public void setFields(List fields) {
            this.fields = fields;
        }
    
    }
    

    Field.java:

    package forum10795793;
    
    import javax.xml.bind.annotation.*;
    
    public class Field {
    
        String mappedField;
    
        @XmlAttribute(name = "mappedField")
        public String getMappedField() {
            return mappedField;
        }
    
        public void setMappedField(String mappedField) {
            this.mappedField = mappedField;
        }
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

提交回复
热议问题