Class Cast Exception when trying to unmarshall xml

2019-01-30 04:55发布

Trying to get past a class cast exception here:

FooClass fooClass = (FooClass ) unmarshaller.unmarshal(inputStream);

throws this exception:

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

I don't understand this - as the class was generated by the xjc.bat tool - and the classes it generated I have not altered at all - so there should be no casting problems here - the unmarshaller should really be giving me back a class that CAN be cast to FooClass.

Any ideas as to what I am doing wrong?

标签: java jaxb jaxb2
14条回答
何必那么认真
2楼-- · 2019-01-30 05:40

Specify @XmlRootElement(name="specifyName", namespace="namespace") to transforming object.

查看更多
甜甜的少女心
3楼-- · 2019-01-30 05:42

Try this:

JAXBContext jc = JAXBContext.newInstance(Foo.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement element = (JAXBElement) unmarshaller.unmarshal( new StringReader(xmlString));
Foo foo = (Foo)element;
查看更多
登录 后发表回答