JAXB annotation – mapping interface and @ xmlelementwrapper
•
Java
I encountered a problem with the JAXB annotation of a field, which is a list and its generic type is an interface When I announce the following:
@XmlAnyElement private List<Animal> animals;
Everything is normal But when I add a wrapper element, for example:
@XmlElementWrapper @XmlAnyElement private List<Animal> animals;
I found that Java objects were grouped correctly, but when I ungrouped documents created by grouping, my list was empty I have released the code below the code to demonstrate this problem
What did I do wrong, or was it a mistake? I've tried version 2.1 12 and 2.2-ea, the results are the same
I am mapping annotated interfaces through examples: 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 {} }
Solution
This is in JAXB 2.1 Bug fixed in 13 Update the library or use JDK 1.7 or later, the problem will be solved
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码