cod*_*ger 6 annotations interface jaxb
我遇到了一个字段的JAXB注释有问题,该字段是一个列表,其泛型类型是一个接口.当我宣布如下:
@XmlAnyElement
private List<Animal> animals;
Run Code Online (Sandbox Code Playgroud)
一切都正常.但是当我添加一个包装元素时,例如:
@XmlElementWrapper
@XmlAnyElement
private List<Animal> animals;
Run Code Online (Sandbox Code Playgroud)
我发现Java对象正确编组,但是当我解组由编组创建的文档时,我的列表是空的.我已经在代码下面发布了演示此问题的代码.
我做错了什么,或者这是一个错误?我已经尝试使用版本2.1.12和2.2-ea,结果相同.
我正在通过示例来映射带有注释的接口: 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 {}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
应该使用@XmlElementRefs({@XmlElementRef(type = Dog.class),@ XMLElementRef(type = Cat.class)})私有List动物;
或者仅使用@XmlAnyElement(lax = true),并将Dog.class,Cat.class添加到JaxbContext
| 归档时间: |
|
| 查看次数: |
18084 次 |
| 最近记录: |