Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jaxb2Marshaller with multiple classes having same @XmlRootElement name

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 ?

like image 564
naiquevin Avatar asked Mar 03 '11 08:03

naiquevin


2 Answers

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);
like image 67
Jtsay Avatar answered Sep 28 '22 15:09

Jtsay


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:

  • http://bdoughan.blogspot.com/2011/03/handling-duplicate-xmlrootelement.html
like image 29
bdoughan Avatar answered Sep 28 '22 16:09

bdoughan