Is there a way to adjust the processing depth in JAXB?

Let's say I have my domain objects, so the XML looks like this:

<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? I want my XML to look like this:

<account id="1">
    <name>Dan</name>
    <friends>
        <friend id="2" />
        <friend id="3" />
    </friends>
</account>
+5
source share
1 answer

You can do this using the XmlJavaTypeAdapter .

Change your 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:

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;
}
+3
source

All Articles