简体   繁体   中英

How to marshall a set with jaxb?

I have the following code:

@XmlRootElement(name = "foo")
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo
{

   @XmlElement
   private String id;

   ...

}

I would like to be able to marshal a Set<Foo> foos into:

<foos>
   <foo>
       <id>bar1</id>
   </foo>
   <foo>
       <id>bar2</id>
   </foo>
</foos>

Do I need a wrapper class? If so, how should it look? Are my annotations correct? How should the marhalling code look like (if you could illustrate this all, that'd be much appreciated)?

If you want to encapsulate any Collection use XmlElementWrapper

@XmlElementWrapper(name="foos")
@XmlElement(name="foo")
private Set<Foo> foos;

By the way you cannot directly marshall a Set so you have to include your Set inside your own class. So if you just want to marshall a set of Foo you have to write a bean like this :

@XmlRootElement(name = "foos")
public class Foos {
    @XmlElement(name="foo")
    private Set<Foo> foo;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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