JAXB Unmarshalling XML Class Cast Exception

2019-02-25 19:43发布

I'm using this JAXB Collection Generics to unmarshall my string xml and return the List type. Here's the methods I used.

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();
}

Example getters and setters:

   @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+"]"; 
    }

}

Main class:

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 thrown

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)

What did I do wrong? Any ideas?Thanks.

1条回答
唯我独甜
2楼-- · 2019-02-25 20:11

Your list is not a list of Person objects as you expect. Due to java's generic type erasure, you're not seeing the error until you try to cast to person in the loop.

Try:

List<Person> p = unmarshalCollection(Person.class,xml);
for(Object person : p ){
   System.out.println(person.getClass());
}

See http://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure

查看更多
登录 后发表回答