JAXB 注释 - 映射接口和 @XmlElementWrapper [英] JAXB Annotations - Mapping interfaces and @XmlElementWrapper

查看:41
本文介绍了JAXB 注释 - 映射接口和 @XmlElementWrapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个字段的 JAXB 注释问题,该字段是一个列表,其泛化类型是一个接口.当我将其声明为:

I am having trouble with JAXB annotations for a field that is a list whose generified type is an interface. When I have it declared such as:

@XmlAnyElement
private List<Animal> animals;

一切正常.但是当我添加一个包装元素时,比如:

Every thing works correctly. But when I add a wrapper element, such as:

@XmlElementWrapper
@XmlAnyElement
private List<Animal> animals;

我发现 Java 对象编组正确,但是当我解组由编组创建的文档时,我的列表是空的.我已在代码下方发布以演示此问题.

I find that the Java object marshals correctly, but when I unmarshal the document created by marshaling, my list is empty. I have posted below the code to demonstrate this problem.

我做错了什么,还是这是一个错误?我已经在 2.1.12 和 2.2-ea 版本中尝试过,结果相同.

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

我正在完成使用位于此处的注释映射接口的示例:https://jaxb.dev.java.net/guide/Mapping_interfaces.html

I am working through the example for mapping interfaces with 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 {}
} 

推荐答案

这是一个错误 已在 JAXB 2.1.13 中修复.更新您的库或使用 JDK 1.7 或更高版本,问题将得到解决.

This is a bug that was fixed in JAXB 2.1.13. Update your libraries or use JDK 1.7 or later and the problem will be solved.

这篇关于JAXB 注释 - 映射接口和 @XmlElementWrapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆