简体   繁体   English

有没有办法在JAXB中配置渲染深度?

[英]Is there a way to configure rendering depth in JAXB?

Let's say I've got my domain objects laid out so the XML looks like this: 假设我的域对象已经布局,所以XML看起来像这样:

<account id="1">
  <name>Dan</name>
  <friends>
    <friend id="2">
      <name>RJ</name>
    </friend>
    <friend id="3">
      <name>George</name>
    </friend>
  </friends>
</account>

My domain object: 我的域名对象:

@XmlRootElement
public class Account {
    @XmlAttribute
    public Long id;
    public String name;

    @XmlElementWrapper(name = "friends")
    @XmlElement(name = "friend")
    public List<Account> friends;
}

Is there an easy way to configure JAXB to render only to a depth of 2? 有没有一种简单的方法可以将JAXB配置为仅渲染到2的深度? Meaning, I'd like my XML to look like this: 意思是,我希望我的XML看起来像这样:

<account id="1">
    <name>Dan</name>
    <friends>
        <friend id="2" />
        <friend id="3" />
    </friends>
</account>

You can do this using an XmlJavaTypeAdapter . 您可以使用XmlJavaTypeAdapter执行此操作。

Change Account as follows: 更改帐户如下:

@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: 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: AccountRef.java:

@XmlRootElement
public class AccountRef 
{ 
    @XmlAttribute
    public Long id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM