如何在JAXB中为返回的集合设置WrapperElement名称?

时间:2013-06-27 17:33:08

标签: java xml jaxb jax-rs

我有一个Web服务,其方法类似于:

@WebMethod(operationName = "getCampusList")
@GET
@Produces({"application/json", "application/xml"})
public List<Campus> getCampusList() {

  List<Campus> campuses = campusService_.getCampusList();

  if(campuses.isEmpty()) {
     throw new WebApplicationException(Response.Status.NOT_FOUND);
   }

   return campuses;
}

Campus是JAXB注释并且工作得很好,但封装的根元素是集合。有没有办法将其改为校园?有什么理由认为这不是一个坏主意吗?下面是当前返回值的片段。

<collection>
  <campus>
    <address>
      <street1>3000 Ivyside Park</street1>
      <city>Altoona</city>
      <state>PA</state>
      <postalCode>16601-3760</postalCode>
    </address>
       <code>AA</code>
       <id>2</id>
       <latitude>40.541118</latitude>
       <longitude>-78.411003</longitude>
       <mapUrl>http://maps.google.com/maps?z=16&q=40.541118,-78.411003</mapUrl>
       <name>Altoona</name>
  </campus>
  <campus>

等...

1 个答案:

答案 0 :(得分:1)

此行为因JAX-RS实现而异,因为它们是在返回集合时提供根元素的行为。您可以返回一个包装器对象,该对象包含使用List<Campus>注释的@XmlRootElement(name="campuses")类型的属性。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Campuses {

    @XmlElement(name="campus")
    private List<Campus> campuses;

}

然后,您将为XML和JSON创建单独的get方法,以获得适当的返回类型。

<强> XML

@GET
@Produces("application/xml")
public Campuses getCampusListXML() {

  List<Campus> campuses = campusService_.getCampusList();

  if(campuses.isEmpty()) {
     throw new WebApplicationException(Response.Status.NOT_FOUND);
   }

   Campuses response = new Campuses();
   response.setCampuses(campuses);
   return response;
}

<强> JSON

@GET
@Produces("application/json")
public List<Campus> getCampusListJSON() {

  List<Campus> campuses = campusService_.getCampusList();

  if(campuses.isEmpty()) {
     throw new WebApplicationException(Response.Status.NOT_FOUND);
   }

   return campuses;
}