[英]JAXB Unmarshalling XML Class Cast Exception
我正在使用此JAXB Collection泛型来解组字符串xml并返回List类型。 这是我使用的方法。
public static <T> List<T> unmarshalCollection(Class<T> cl, String s)
throws JAXBException {
return unmarshalCollection(cl, new StringReader(s));
}
public static <T> List<T> unmarshalCollection(Class<T> cl, Reader r)
throws JAXBException {
return unmarshalCollection(cl, new StreamSource(r));
}
private static <T> List<T> unmarshalCollection(Class<T> cl, Source s)
throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(JAXBCollection.class, cl);
Unmarshaller u = ctx.createUnmarshaller();
JAXBCollection<T> collection = u.unmarshal(s, JAXBCollection.class).getValue();
return collection.getItems();
}
示例获取器和设置器:
@XmlRootElement(name = "person")
class Person{
private String firstName;
private String lastName;
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [firstName ="+firstName+" , lastName = "+lastName+" , address = "+address+"]";
}
}
主班:
public static void main(String[] args) throws JAXBException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><firstName>Foo</firstName><lastName>Bar</lastName><address>U.S</address></person>";
List<Person> p = unmarshalCollection(Person.class,xml);
for(Person person : p ){
System.out.println(person);
}
}
抛出异常
Exception in thread "main" java.lang.ClassCastException: org.apache.xerces.dom.ElementNSImpl cannot be cast to com.Person
at com.JAXBUtil.main(JAXBUtil.java:62)
我做错了什么? 有什么想法吗?
您的列表不是您期望的Person对象的列表。 由于Java的通用类型擦除,在尝试强制转换为循环中的人员之前,您不会看到该错误。
尝试:
List<Person> p = unmarshalCollection(Person.class,xml);
for(Object person : p ){
System.out.println(person.getClass());
}
参见http://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.