I have a Shape class, and a Circle and Square subclasses. Then I have a Container class that has a List<Shape> shapes field.
I'm doing XML serialization with Jackson, and I'm getting
<shapes><shape radius=".."><shape w=".." h=".."></shapes>
...but what I really want is
<shapes><circle radius=".."><square w=".." h=".."></shapes>
I've tried annotating shapes with
@XmlElements({
@XmlElement(type = Circle.class),
@XmlElement(type = Square.class)
})
...but that just gives me
<shapes><shapes><Circle radius=".."></shapes><shapes><Square w=".." h=".."></shapes></shapes>
...so it's almost right, but those wrappers are annoying. Is there any way of getting what I want, even if it means changing my JAXB implementation?
One of the options is to use @XmlElementRef annotation. Excerpt from javadoc:
This annotation dynamically associates an XML element name with the JavaBean property. When a JavaBean property is annotated with XmlElement, the XML element name is statically derived from the JavaBean property name. However, when this annotation is used, the XML element name is derived from the instance of the type of the JavaBean property at runtime.
So, you can do something like this:
@XmlRootElement
class Container {
//...
//without XmlElementWrapper <shapes> element will be omitted
@XmlElementWrapper(name="shapes")
@XmlElementRef
public List<Shape> getShape() {
//your logic here
}
}
Check out the constraints in javadoc. You might need to annotate Shape, Circle and Square with @XmlRootElement for this to work:
@XmlRootElement
class Circle {
//no-arg constructor
Circle() {
}
}
You can try something like this. I hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With