Richard Hart

Head of Something @ Somewhere
Kent, UK

My Music
My Photos

LinkedIn
Mastodon

Spring Boot JAXB unable to marshal type error

Test Working with a SOAP API with Spring Boot WS. I was getting the following error trying to create the request.

com.sun.istack.SAXException2: unable to marshal type "com.ur-ban.GetSubscriptioninfo" as an element because it is missing an @XmlRootElement annotation

I was originally directly using the JAXB generated classes to form my requests:

GetSubscriptioninfo subscriptionInfo = new GetSubscriptioninfo();
subscriptionInfo.setSubscriptionId(1);

GetSubscriptioninfoResponse subscriptionInfoResponse = 
  (GetSubscriptioninfoResponse) getWebServiceTemplate()
      .marshalSendAndReceive("http://www.ur-ban.com/subscription", subscriptionInfo);

The correct way is to use the provided JAXB ObjectFactory:

ObjectFactory objectFactory = new ObjectFactory();
GetSubscriptioninfo subscriptionInfo = objectFactory.createGetSubscriptioninfo();
subscriptionInfo.setSubscriptionId(1);

GetSubscriptioninfoResponse subscriptionInfoResponse = 
  (GetSubscriptioninfoResponse) getWebServiceTemplate()
      .marshalSendAndReceive("http://www.ur-ban.com/subscription", subscriptionInfo);

But to prevent marshalling errors you need to wrap your object in a JAXBElement object:

ObjectFactory objectFactory = new ObjectFactory();
GetSubscriptioninfo subscriptionInfo = objectFactory.createGetSubscriptioninfo();
subscriptionInfo.setSubscriptionId(1);

JAXBElement jaxbGetSubscriptionInfo = objectFactory.createGetSubscriptioninfo(subscriptionInfo);

GetSubscriptioninfoResponse subscriptionInfoResponse = 
  (GetSubscriptioninfoResponse) getWebServiceTemplate()
      .marshalSendAndReceive("http://www.ur-ban.com/subscription", jaxbGetSubscriptionInfo);