Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException while Unmarshalling XML with JAXB

I have generated java classes using xjc from an xsd where the root element was A of type AType.

The root element generated by jaxb is AType & no class A has been generated.

When I try to unmarshall an xml corresponding to that xsd and cast the JaxbElement it is throwing a cast exception:

Snippet:

JAXBContext jaxbContext = JAXBContext.newInstance(Class.forName("AType"));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
AType aType = (AType) unmarshaller.unmarshal(new ByteArrayInputStream(xmlString.getBytes()));

Exception:

java.lang.ClassCastException: javax.xml.bind.JAXBElement

Same code for other cases execute properly and successfully deserialize.

How can I find unmarshal() gives me object of what type? I have no clue what's going wrong in this situation, I've tried printing out fields in that jaxbElement but it was not very useful!

like image 306
Rahul Thakur Avatar asked Jan 16 '23 15:01

Rahul Thakur


1 Answers

If the class of the root element (here: AType) doesn't contain the XmlRootElement-annotation, then the returned root element gets wrapped in a JAXBElement and you have to use its getValue()-method to get the root element.

AFAIK, XJC will only generate the XmlRootElement-annotation if the type of the root element is an anonymous type.

like image 153
Puce Avatar answered Jan 30 '23 23:01

Puce