JAXB Annotations - Mapping Interfaces and @XmlElementWrapper

I'm having problems with JAXB annotations for a field, which is a list whose generic type is an interface. When I declare this, for example:

@XmlAnyElement private List<Animal> animals; 

Everything is working correctly. But when I add a shell element, for example:

 @XmlElementWrapper @XmlAnyElement private List<Animal> animals; 

I find that Java object markers are correct, but when I cancel a document created by marshaling, my list is empty. I posted below code to demonstrate this problem.

Am I doing something wrong, or is this a mistake? I tried it with versions 2.1.12 and 2.2-ea with the same result.

I am working on an example to map interfaces to the annotations located here: https://jaxb.dev.java.net/guide/Mapping_interfaces.html

 @XmlRootElement class Zoo { @XmlElementWrapper @XmlAnyElement(lax = true) private List<Animal> animals; public static void main(String[] args) throws Exception { Zoo zoo = new Zoo(); zoo.animals = new ArrayList<Animal>(); zoo.animals.add(new Dog()); zoo.animals.add(new Cat()); JAXBContext jc = JAXBContext.newInstance(Zoo.class, Dog.class, Cat.class); Marshaller marshaller = jc.createMarshaller(); ByteArrayOutputStream os = new ByteArrayOutputStream(); marshaller.marshal(zoo, os); System.out.println(os.toString()); Unmarshaller unmarshaller = jc.createUnmarshaller(); Zoo unmarshalledZoo = (Zoo) unmarshaller.unmarshal(new ByteArrayInputStream(os.toByteArray())); if (unmarshalledZoo.animals == null) { System.out.println("animals was null"); } else if (unmarshalledZoo.animals.size() == 2) { System.out.println("it worked"); } else { System.out.println("failed!"); } } public interface Animal {} @XmlRootElement public static class Dog implements Animal {} @XmlRootElement public static class Cat implements Animal {} } 
+6
interface annotations jaxb
source share
5 answers

Use @XmlElementRefs ({@XmlElementRef (type = Dog.class), @XmlElementRef (type = Cat.class)}) personal list of animals;

or use @XmlAnyElement (only lax = true) and add Dog.class, Cat.class to JaxbContext

+8
source share

When I run your test program using jdk1.6.0_20, it works, and I get the following output:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <zoo><animals><dog/><cat/></animals></zoo> it worked 
0
source share

Have you tried putting your annotations into your accessories? I also had a problem with @XmlElementWrapper, but I decided to solve it by putting the annotation of my recipient instead of annotating the field declaration.

0
source share

When I run your test program using jdk1.6.0_20, it does not work, however after changing the annotation for the list from @XmlAnyElement(lax = true) to @XmlElementRefs({ @XmlElementRef(type=Dog.class), @XmlElementRef(type=Cat.class)}) it works. It doesn't matter that Dog.class and Cat.class are added to JAXBContext or not.

0
source share

All Articles