java.lang.ClassCastException:javax.xml.bind.JAXBElement无法强制转换为

时间:2016-03-18 15:15:58

标签: spring jaxb spring-boot unmarshalling

我使用Spring启动来调用web服务。

我的配置类如下:

@Configuration
public class ClientAppConfig {
@Bean
public Jaxb2Marshaller marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan("com.client.stub");
    return marshaller;
}

@Bean
public ARTestClient arTestClient(Jaxb2Marshaller marshaller) {
    ARTestClient client = new ARTestClient();
    client.setDefaultUri("uri");
    client.setMarshaller(marshaller);
    client.setUnmarshaller(marshaller);
   return client;
}

我呼叫服务如下:

    OutputMessageType response = (OutputMessageType) getWebServiceTemplate().marshalSendAndReceive(
            inputMessageType, new SoapActionCallback("http://Serviceuri"));

我收到以下错误:

   [2016-03-18 14:45:43.697] boot - 10272 ERROR [http-nio-8080-exec-1] --- [dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
  [Request processing failed; nested exception is java.lang.ClassCastException: javax.xml.bind.JAXBElement 
  cannot be cast to com.wfs.client.stub.ar.OutputMessageType] with root cause

如何解析webservice的输出????? 我如何为响应设置unmarshaller?

3 个答案:

答案 0 :(得分:16)

有趣的我刚刚遇到了同样的问题,这就是我所做的:

将您的回复转换为

JAXBElement<OutputMessageType>

所以结果将是

JAXBElement<OutputMessageType> response = (JAXBElement<OutputMessageType>) getWebServiceTemplate().marshalSendAndReceive(
        inputMessageType, new SoapActionCallback("http://Serviceuri"));
// Then just call
System.out.println(response.getValue());

我和你的配置差不多。我还在试图弄清楚为什么会有ClassCastException。至少我们有一个解决方法......

答案 1 :(得分:5)

如果今天仍然有用,有一种方法可以在配置文件中解决此问题。而不是在以下行中使用 .setPackagesToScan marshaller.setPackagesToScan("com.client.stub")
考虑使用 .setClassesToBeBound
但是,您需要在您的包装下引用每个类(将用于编组和解组):

   marshaller.setClassesToBeBound(new Class[] { 
       com.client.stub.Foo.class,
       com.client.stub.Bar.class,
       com.client.stub.Baz.class
   });

无需转换为JAXBElement。

答案 2 :(得分:1)

    JAXBElement<OutputMessageType> response = (JAXBElement<OutputMessageType>) 
    getWebServiceTemplate().marshalSendAndReceive(
    inputMessageType, new SoapActionCallback("http://Serviceuri"));
    // Then just call 
     System.out.println(response.getValue());

在我的情况下效果很好

相关问题