Convert Polymorphic Object to XML using JAX-B
When you use polymorphism in your classes and you want to convert your object to XML using JAX-B, here is an example how to.
Abstract Animal Class
package com.memorynotfound.xml.jaxb;
public abstract class Animal {
}
Cat Inherits from Animal
package com.memorynotfound.xml.jaxb;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "cat")
public class Cat extends Animal {
}
Dog Inherits from Animal
package com.memorynotfound.xml.jaxb;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "dog")
public class Dog extends Animal {
}
Root entity class for converting list of animals
package com.memorynotfound.xml.jaxb;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "root")
public class Root {
private List<Animal> animals;
public List<Animal> getAnimals() {
return animals;
}
@XmlElementWrapper(name = "animals")
@XmlElements({
@XmlElement(name = "dog", type = Dog.class),
@XmlElement(name = "cat", type = Cat.class)
})
public void setAnimals(List<Animal> animals) {
this.animals = animals;
}
}
Convert Polymorphic Object to XML
package com.memorynotfound.xml.jaxb;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.util.ArrayList;
import java.util.List;
public class PolymorphismObjectXml {
public static void main(String... args) throws JAXBException {
// create object
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog());
animals.add(new Cat());
Root root = new Root();
root.setAnimals(animals);
// create jaxb context
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
// create jaxb marshaller
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// pretty print xml
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// marshal object
jaxbMarshaller.marshal(root, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<animals>
<dog/>
<cat/>
</animals>
</root>