Using Jaxb2Marshaller with multiple classes having same @XmlRootElement name
Asked Answered
I

2

10

I am working on a web service using spring-mvc and Jaxb2Marshaller.

I have two classes, both annotated with the same @XmlRootElement name

@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

Now the request that uses Bar works fine. But the one that uses Foo throws a ClassCastException exception during unmarshalling with message Bar cannot be cast to Foo

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

However I am also having multiple classes annotated with @XmlRootElement(name="response") and marshalling the response doesn't give any problem.

Is there a way to specify the class to be used by the jaxb2Marshaller for unmarshalling ?

Invest answered 3/3, 2011 at 8:28 Comment(1)
No, there's no way to do that. You need to refactor your design to keep them distinct from each other.Signe
A
4

You can pass the class to Jaxb2Marshaller before unmarshal:

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

Foo request = (Foo) jaxb2Marshaller.unmarshal(source);
Athalie answered 13/5, 2016 at 1:23 Comment(0)
F
3

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:

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

For more information see:

Foreclosure answered 14/3, 2011 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.