[英]Using Jaxb2Marshaller with multiple classes having same @XmlRootElement name
I am working on a web service using spring-mvc and Jaxb2Marshaller. 我正在使用spring-mvc和Jaxb2Marshaller开发Web服务。
I have two classes, both annotated with the same @XmlRootElement
name 我有两个类,都用相同的
@XmlRootElement
名称注释
@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 所有三个类(AbstractRequest,Foo,Bar)以相同的顺序包含在classesToBeBound列表中
Now the request that uses Bar works fine. 现在,使用Bar的请求可以正常工作。 But the one that uses Foo throws a ClassCastException exception during unmarshalling with message
Bar cannot be cast to Foo
但是,使用Foo的用户在将消息
Bar cannot be cast to Foo
解组时Bar cannot be cast to Foo
抛出ClassCastException异常。
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
我猜
发生了这种情况,因为Bar是覆盖Foo的,因为它是在Foo之后写在spring-servlet.xml文件中要绑定的类列表中的
However I am also having multiple classes annotated with @XmlRootElement(name="response")
and marshalling the response doesn't give any problem. 但是我也有多个用
@XmlRootElement(name="response")
注释的类,并且整理响应不会带来任何问题。
Is there a way to specify the class to be used by the jaxb2Marshaller for unmarshalling ? 有没有办法指定jaxb2Marshaller用于解组的类?
You can pass the class to Jaxb2Marshaller before unmarshal: 您可以在解组之前将类传递给Jaxb2Marshaller:
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: 您可以从Jaxb2Marshaller创建一个Unmarshaller,然后可以将要解组的类作为参数传递给采用Source的unmarshal方法:
Source source = new StreamSource(new StringReader(body));
Unmarshaller unmarshaller = jaxb2Marshaller.createUnmarshaller();
Foo request = (Foo) unmarshaller.unmarshal(source, Foo.class).getValue();
For more information see: 有关更多信息,请参见:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.