开发者

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 ?


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:

  • http://bdoughan.blogspot.com/2011/03/handling-duplicate-xmlrootelement.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜