【问题标题】:JAXB Unmarshalling XML Class Cast ExceptionJAXB 解组 XML 类强制转换异常
【发布时间】:2014-08-15 09:34:21
【问题描述】:

我正在使用这个JAXB Collection Generics 来解组我的字符串 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();
}

getter 和 setter 示例:

   @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)

我做错了什么?有什么想法吗?谢谢。

【问题讨论】:

    标签: java xml xml-parsing jaxb


    【解决方案1】:

    您的列表不是您期望的 Person 对象列表。由于 java 的泛型类型擦除,在您尝试在循环中强制转换为 person 之前,您不会看到错误。

    试试:

    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

    【讨论】:

    • 我只是将返回类型更改为 List 就可以了!非常感谢。
    • 嗯......这对我来说听起来像是一个糟糕的解决方案。我是在向你指出问题,而不是解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多