java jaxb 集合,使用JAXB映射包含超类和子类的Java集合

这篇博客介绍了如何利用Java的JAXB库将具有共同超类的对象正确地映射到XML中。示例展示了如何为`Person`类及其包含的`Identity`子类如`Blue`和`Green`定义注解,以得到期望的XML结构。目前的代码输出并不符合需求,通过添加`@XmlElementRef`注解到`identities`属性,可以解决这个问题。
摘要由CSDN通过智能技术生成

I'm trying to produce something like this with JAXB:

Foo

Bar

The child elements of all stem from a common super-class.

In Java it's like this:

@XmlRootElement(name = "person")

public class Person {

public String firstName;

public String lastName;

@XmlElementWrapper(name = "identities")

public Set identities = new HashSet();

}

Where Identity is a super class for Blue, Green and some others.

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 {}

How do I properly annotate the classes to get what I need? Currently, the output is like so:

解决方案

Simply modify your example to use the @XmlElementRef annotation on the identities property.

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 identities = new HashSet();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值