I can't understand why this JAXB IllegalAnnota

2019-01-21 22:56发布

This is my XML file:

<fields>
    <field mappedField="Num">
    </field>

    <field mappedField="Type">      
    </field>    
</fields>

I made 2 classes to parse it (Fields.java and Field.java):

@XmlRootElement(name = "fields")
public class Fields {

    @XmlElement(name = "field")
    List<Field> fields = new ArrayList<Field>();
        //getter, setter
}

and

public class Field {

    @XmlAttribute(name = "mappedField")
    String mappedField;
    /getter,setter
}

But I get this exception.

[INFO] com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
[INFO]  at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66) ~[na:1.6.0_07]
[INFO]  at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:422) ~[na:1.6.0_07]
[INFO]  at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:270) ~[na:1.6.0_07]

I can't understand why this exception rises. Exception is here:

JAXBContext context = JAXBContext.newInstance(Fields.class);

I use JDK 1.6_0.0.7. Thanks.

8条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-21 23:56

This is because, by default, Jaxb when serializes a pojo, looks for the annotations over the public members(getters or setters) of the properties. But, you are providing annotations on fields. so, either change and set the annotations on setters or getters of properties, or sets the XmlAccessortype to field.

Option 1::

@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
        //getter, setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       @XmlAttribute(name = "mappedField")
       String mappedField;
       //getter,setter
}

Option 2::

@XmlRootElement(name = "fields")
public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        public List<Field> getFields() {

        }

        //setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       String mappedField;

       @XmlAttribute(name = "mappedField")
       public String getMappedField() {

       }

        //setter
}

For more detail and depth, check the following JDK documentation http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/XmlAccessorType.html

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-21 23:57

I had this same issue, I was passing a spring bean back as a ResponseBody object. When I handed back an object created by new, all was good.

查看更多
登录 后发表回答