JAXB list mappings
If you have an object to serialize to XML using JAXB which contains a List, for example:
List<String> things;
public List<String> getThings() {
return things;
}
public void setThings(List<String> things) {
this.things = things;
}
the default serialization for this is into a list of elements as follows:
<things>thing 1</things>
<things>thing 2</things>
<things>thing 3</things>
This is not quite what I want, because I want it to be clear to the consumer that there's a list and that each item in the list is intuitively named: e.g. having a wrapper called <things> and each item being in an element called <thing>. To do this, use some JAXB annotations to set the element name and also a name for a wrapper element to hold the list. For example:
@XmlElementWrapper(name="things")
@XmlElement(name="thing")
Note that these annotations need to be on the getter method, it won't work if you put them on the variable declaration (or on the setter method for that matter). What this will give you (if you initialize the list with data) is something like this:
<things>
<thing>thing 1</thing>
<thing>thing 2</thing>
<thing>thing 3</thing>
</things>
List<String> things;
public List<String> getThings() {
return things;
}
public void setThings(List<String> things) {
this.things = things;
}
the default serialization for this is into a list of elements as follows:
<things>thing 1</things>
<things>thing 2</things>
<things>thing 3</things>
This is not quite what I want, because I want it to be clear to the consumer that there's a list and that each item in the list is intuitively named: e.g. having a wrapper called <things> and each item being in an element called <thing>. To do this, use some JAXB annotations to set the element name and also a name for a wrapper element to hold the list. For example:
@XmlElementWrapper(name="things")
@XmlElement(name="thing")
Note that these annotations need to be on the getter method, it won't work if you put them on the variable declaration (or on the setter method for that matter). What this will give you (if you initialize the list with data) is something like this:
<things>
<thing>thing 1</thing>
<thing>thing 2</thing>
<thing>thing 3</thing>
</things>
Labels: JAXB

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
Links to this post:
Create a Link
<< Home