javax.xml.bind.JAXBElement unmarshal error

By W.ZH Apr 2011

Issue:

When I use JAXB 2.0 to unmarshal an XML to a java Object, I get an error that :

java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to com.oracle.daps.Path.

the code is sth like this :

JAXBContext jc = JAXBContext.newInstance(“com.oracle.daps.obj”);

Unmarshaller u = jc.createUnmarshaller();

MyJavaObj jo = (MyJavaObj) u.unmarshal(new StreamSource(new StringReader(“myxml.xml”)));

Reason:

In infct when i run this kind of code when using jaxb 1.0 , i do not get any error, but later when i update my XML xsd schema and try to generate a set of new JAVA obj by new xsd, I use the JAXB 2 to do that, so my unmarshal get this error, reason is that JAXBElement  in fact contain the obj in its value, i need a layer more to convert this XML to Java Obj.

Solution:

JAXBContext jc = JAXBContext.newInstance(“com.oracle.daps.obj”);

Unmarshaller u = jc.createUnmarshaller();

MyJavaObj jo = (MyJavaObj) ((
JAXBElement) u.unmarshal(new StreamSource(new StringReader(“myxml.xml”)))).getValue()

Advertisements