Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JAXB解组XML类强制转换异常_Java_Xml_Xml Parsing_Jaxb - Fatal编程技术网

Java JAXB解组XML类强制转换异常

Java JAXB解组XML类强制转换异常,java,xml,xml-parsing,jaxb,Java,Xml,Xml Parsing,Jaxb,我用它来解组字符串xml并返回列表类型。 以下是我使用的方法 public static <T> List<T> unmarshalCollection(Class<T> cl, String s) throws JAXBException { return unmarshalCollection(cl, new StringReader(s)); } public static <T> List<T> unm

我用它来解组字符串xml并返回列表类型。 以下是我使用的方法

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();
}
主要类别:

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

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

您的列表并不像您所期望的那样是个人对象列表。由于java的泛型类型擦除,在尝试向循环中的人强制转换之前,您不会看到错误

尝试:

List p=unmarshalCollection(Person.class,xml);
对象(人:p){
System.out.println(person.getClass());
}

请参见

我只是将返回类型更改为List,它就可以工作了!非常感谢。嗯。。。对我来说,这听起来是个糟糕的解决办法。我指的是问题,不是解决问题。
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)
List<Person> p = unmarshalCollection(Person.class,xml);
for(Object person : p ){
   System.out.println(person.getClass());
}