Jersey可以生成List 但不能响应Response.ok(List )。build()?

泽西1.6可以生产:

@Path("/stock") public class StockResource { @GET @Produces(MediaType.APPLICATION_JSON) public List 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(); } } 

给出错误: A message body writer for Java class java.util.ArrayList, and Java type class java.util.ArrayList, and MIME media type application/json was not found

这可以防止使用HTTP状态代码和标头。

可以通过以下方式在List嵌入List

 @Path("/stock") public class StockResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response get() { Stock stock = new Stock(); stock.setQuantity(3); GenericEntity> entity = new GenericEntity>(Lists.newArrayList(stock)) {}; return Response.ok(entity).build(); } } 

客户端必须使用以下行来获取List

 public List 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>() { }); } 

由于某种原因,GenericType修复程序不起作用。 但是,由于类型擦除是针对集合而不是针对arrays完成的,因此这很有用。

  @GET @Produces(MediaType.APPLICATION_XML) public Response getEvents(){ List events = eventService.getAll(); return Response.ok(events.toArray(new Event[events.size()])).build(); } 

我使用AsyncResponse的方法的解决方案

 @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void list(@Suspended final AsyncResponse asyncResponse) { asyncResponse.setTimeout(10, TimeUnit.SECONDS); executorService.submit(() -> { List res = super.listProducts(); Product[] arr = res.toArray(new Product[res.size()]); asyncResponse.resume(arr); }); }