假设我的域对象已经布局,所以XML看起来像这样:
<account id="1">
<name>Dan</name>
<friends>
<friend id="2">
<name>RJ</name>
</friend>
<friend id="3">
<name>George</name>
</friend>
</friends>
</account>
我的域名对象:
@XmlRootElement
public class Account {
@XmlAttribute
public Long id;
public String name;
@XmlElementWrapper(name = "friends")
@XmlElement(name = "friend")
public List<Account> friends;
}
是否有一种简单的方法可以将JAXB配置为仅渲染到2的深度?意思是,我希望我的XML看起来像这样:
<account id="1">
<name>Dan</name>
<friends>
<friend id="2" />
<friend id="3" />
</friends>
</account>
答案 0 :(得分:3)
您可以使用XmlJavaTypeAdapter。
执行此操作更改帐户如下:
@XmlRootElement
public class Account {
@XmlAttribute
public Long id;
public String name;
@XmlElementWrapper(name = "friends")
@XmlElement(name = "friend")
@XmlJavaTypeAdapter( value = AccountAdapter.class )
public List<Account> friends;
}
AccountAdapter.java:
public class AccountAdapter extends XmlAdapter<AccountRef, Account>
{
@Override
public AccountRef marshal(Account v) throws Exception
{
AccountRef ref = new AccountRef();
ref.id = v.id;
return ref;
}
@Override
public Account unmarshal(AccountRef v) throws Exception
{
// Implement if you need to deserialize
}
}
AccountRef.java:
@XmlRootElement
public class AccountRef
{
@XmlAttribute
public Long id;
}