1

我有一个 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>

ETC...

4

1 回答 1

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;
}
于 2013-06-27T17:53:23.560 回答