如何使用JAXB注释将Java列表转换为XML?

时间:2016-02-10 12:40:10

标签: java xml jaxb

如何翻译Java列表

List<String> locations

进入XML表示

...

<locations>
    <location>/bob/app/l1.xml</location>
    <location>/bob/app/l2.xml</location>
    <location>/bob/app/l3.xml</location>
</locations>

...

并同时保存JSON兼容性格式:

...

"locations": ["/bob/app/l1.xml","/bob/app/l2.xml"]

...    

我使用Spring和我当前获得响应的XML格式

...
<locations>/bob/app/l1.xml</locations>
<locations>/bob/app/l2.xml</locations>
...

我使用JAXB注释

@XmlElement(name = "locations")
public void setLocations(List<String> locations) {
    this.locations = locations;
}

UPD

我找到了解决方案。我只需要使用

@XmlElementWrapper(name = "locations")
@XmlElement(name = "location")
public List<String> getLocations() {
    return locations;
}

1 个答案:

答案 0 :(得分:0)

正如@renju所说,你可以像这样包装..

@XmlRootElement(name="locations")
public class Locations {

    @XmlElement(name="location")
    private List<String> locations;

    //setter and getter
}