Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB/Jackson XML generic serialization

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?

like image 409
Edu Garcia Avatar asked Apr 25 '26 00:04

Edu Garcia


2 Answers

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() {
    }
}
like image 124
default locale Avatar answered Apr 26 '26 12:04

default locale


You can try something like this. I hope it helps

like image 21
Serhii Kariaka Avatar answered Apr 26 '26 13:04

Serhii Kariaka