您的位置:首页 > 博客中心 > 电脑问题 >

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions 属性className已存在, 但未在 @XmlType.propOrder 中指定 this problem is related to the following location: at pub

时间:2022-03-18 10:33

学习CXF的JAXB时遇到的小问题

利用JAXB把java对象 转换为xml

package com.example.test;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="student")
@XmlType(name = "student", propOrder = { "name","ClassName" })
public class Student {
private String name;
private String ClassName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return ClassName;
}
public void setClassName(String className) {
className = className;
}

}

 工具类

 

package com.example.test;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBUtil {
public static String toXml(Object o){
StringWriter writer = new StringWriter();
try {
Class obj = o.getClass();
JAXBContext jaxbContext = JAXBContext.newInstance(obj);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(o, writer);
} catch (JAXBException e) {
e.printStackTrace();
}
return writer.toString();

}
}

 

测试类

package com.example.test;

public class JaxbHelperTest {
public static void main(String[] args) {
Student stu = new Student();

stu.setName("小明");

stu.setClassName("三一班");

System.out.println(JAXBUtil.toXml(stu));


}
}

 运行后报错  实在是大意了,最后把实体类的 属性ClassName 改为 className 问题解决,应该是实体类的属性第一个字母不能大写。


package com.example.test;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name="student")
@XmlType(name = "student", propOrder = { "name","className" })
public class Student {
private String name;
private String className;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
className = className;
}

}

 

热门排行

今日推荐

热门手游