I am working on a web service using spring-mvc and Jaxb2Marshaller.
I have two classes, both annotated with the same @XmlRootElement
name
@XmlRootElement(name="request")
class Foo extends AstractRequest {
}
@XmlRootElement(name="request")
class Bar extends AbstractRequest {
}
All three classes (AbstractRequest, Foo, Bar) are included in the classesToBeBound list in the same order
Now the request that uses Bar works fine. But the one that uses Foo throws a ClassCastException exception during unmarshalling with message Bar cannot be cast to Foo
The controller code is this,
Source source = new StreamSource(new StringReader(body));
Foo request = (Foo) this.jaxb2Marshaller.unmarshal(source);
I guess this is happening because Bar is kind of overriding Foo since it's written after Foo in the list of classes to be bound in the spring-servlet.xml file
However I am also having multiple classes annotated with @XmlRootElement(name="response")
and marshalling the response doesn't give any problem.
Is there a way to specify the class to be used by the jaxb2Marshaller for unmarshalling ?
You can pass the class to Jaxb2Marshaller before unmarshal:
Source source = new StreamSource(new StringReader(body));
jaxb2Marshaller.setMappedClass(Foo.class);
Foo request = (Foo) jaxb2Marshaller.unmarshal(source);
You can create an Unmarshaller from the Jaxb2Marshaller, then you can pass the class you want to unmarshal as a parameter to the unmarshal method that takes a Source:
Source source = new StreamSource(new StringReader(body));
Unmarshaller unmarshaller = jaxb2Marshaller.createUnmarshaller();
Foo request = (Foo) unmarshaller.unmarshal(source, Foo.class).getValue();
For more information see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With