问题描述
Jersey 1.6 可以生产:
Jersey 1.6 can produce:
@Path("/stock") public class StockResource { @GET @Produces(MediaType.APPLICATION_JSON) public List<Stock> get() { Stock stock = new Stock(); stock.setQuantity(3); return Lists.newArrayList(stock); } }
但不能这样做:
@Path("/stock") public class StockResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response get() { Stock stock = new Stock(); stock.setQuantity(3); return Response.ok(Lists.newArrayList(stock)).build(); } }
给出错误:找不到 Java 类 java.util.ArrayList、Java 类型类 java.util.ArrayList 和 MIME 媒体类型 application/json 的消息正文编写器
这会阻止使用 HTTP 状态代码和标头.
This prevent the use of HTTP status code and headers.
推荐答案
可以通过以下方式在响应中嵌入 List
It is possible to embed a List<T> in a Response the following way:
@Path("/stock") public class StockResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response get() { Stock stock = new Stock(); stock.setQuantity(3); GenericEntity<List<Stock>> entity = new GenericEntity<List<Stock>>(Lists.newArrayList(stock)) {}; return Response.ok(entity).build(); } }
客户端必须使用以下行来获取List<T>:
The client have to use the following lines to get the List<T>:
public List<Stock> getStockList() { WebResource resource = Client.create().resource(server.uri()); ClientResponse clientResponse = resource.path("stock") .type(MediaType.APPLICATION_JSON) .get(ClientResponse.class); return clientResponse.getEntity(new GenericType<List<Stock>>() { }); }