【问题标题】:Mapping Java collections which contains super- and sub-types with JAXB使用 JAXB 映射包含超类型和子类型的 Java 集合
【发布时间】:2010-10-29 18:19:10
【问题描述】:

我正在尝试使用 JAXB 生成类似的东西:

  <person>
    <firstName>Foo</firstName>
    <lastName>Bar</lastName>
    <identities>
      <green id="greenId">
            <some_elements....
      </green>
      <blue id="blueId"/>
    </identities>

&lt;identities&gt; 的子元素都源于一个共同的超类。

在 Java 中是这样的:

@XmlRootElement(name = "person")
public class Person {
    public String firstName; 
    public String lastName;
    @XmlElementWrapper(name = "identities")
    public Set<Identity> identities = new HashSet<Identity>();
}

其中IdentityBlueGreen 和其他一些的超类。

public class Identity {
    @XmlID
    @XmlAttribute
    public String id; 
}

@XmlRootElement(name = "blue")
public class Blue extends Identity {
    public String oneOfManyFields;
}

@XmlRootElement(name = "green")
public class Green extends Identity {}

如何正确注释类以获得我需要的内容?目前,输出是这样的:

<identities>
    <identities id="0815"/>
</identities>

【问题讨论】:

    标签: java collections jaxb


    【解决方案1】:

    只需修改您的示例以在 identities 属性上使用 @XmlElementRef 注释。

    import java.util.HashSet;
    import java.util.Set;
    
    import javax.xml.bind.annotation.XmlElementRef;
    import javax.xml.bind.annotation.XmlElementWrapper;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name = "person")
    public class Person {
        public String firstName; 
        public String lastName;
        @XmlElementWrapper(name = "identities")
        @XmlElementRef
        public Set<Identity> identities = new HashSet<Identity>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2015-08-02
      相关资源
      最近更新 更多