java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to

Viewed 21828

I am using Spring boot to call a webservice.

my config class is as:

@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;
}

i am calling service as following:

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

I am getting following error:

   [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

How to unMarshal the output from webservice????? How do i set unmarshaller for the response??

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

worked well for my case

It all depends on how you define the root element in your xsd. If you define it as

<element name="myRootElement" type="tns:myRootElementType" />

And then generate the JAXB classes - the unmarshaller will retrun JAXBElement after unmarshalling. And to get the root element you will have to call JAXBElement.getValue();

But if you define your root element as -

<element name="myRootElement">
       <complextType>
           Your definition of complex type - whatever it is
       </complexType>
<element>

and then generate your JAXB classes - the unmarshaller will return the entire object of your JAXB generated class that represents your root element. In this case it won't return object of JAXBElement.

You can check the documentation of Unmarshaller -

https://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.html

Specifically sections - Unmarshal a root element that is globally declared and Unmarshal by Declared Type

Remember - after making changes to your xsd - you will have to regenerate JAXB classes.

I hope this solves your problem.

Related