10

我正在使用 spring-mvc 和 Jaxb2Marshaller 开发 Web 服务。

我有两个类,都用相同的@XmlRootElement名称注释

@XmlRootElement(name="request")
class Foo extends AstractRequest {

}

@XmlRootElement(name="request")
class Bar extends AbstractRequest {

}

所有三个类(AbstractRequest、Foo、Bar)都以相同的顺序包含在 classesToBeBound 列表中

现在使用 Bar 的请求工作正常。但是使用 Foo 的那个在使用消息解组期间抛出 ClassCastException 异常Bar cannot be cast to Foo

控制器代码是这样的,

Source source = new StreamSource(new StringReader(body));
Foo request = (Foo) this.jaxb2Marshaller.unmarshal(source); 

我猜这是因为 Bar 是一种覆盖 Foo 的原因,因为它是在要绑定到 spring-servlet.xml 文件中的类列表中的 Foo 之后编写的

但是,我也有多个带有注释的类,@XmlRootElement(name="response")并且编组响应没有任何问题。

有没有办法指定 jaxb2Marshaller 用于解组的类?

4

2 回答 2

4

您可以在解组之前将类传递给 Jaxb2Marshaller:

Source source = new StreamSource(new StringReader(body));
jaxb2Marshaller.setMappedClass(Foo.class);

Foo request = (Foo) jaxb2Marshaller.unmarshal(source);
于 2016-05-13T01:23:52.237 回答
3

您可以从 Jaxb2Marshaller 创建一个 Unmarshaller,然后您可以将要解组的类作为参数传递给采用 Source 的 unmarshal 方法:

Source source = new StreamSource(new StringReader(body));
Unmarshaller unmarshaller = jaxb2Marshaller.createUnmarshaller();
Foo request = (Foo) unmarshaller.unmarshal(source, Foo.class).getValue(); 

有关更多信息,请参阅:

于 2011-03-14T13:10:05.373 回答