泽西岛1.6可以产生:
@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();
}
}
给出错误: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状态代码和标头。
答案 0 :(得分:25)
可以通过以下方式在响应中嵌入List<T>
:
@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>
:
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>>() {
});
}
答案 1 :(得分:8)
由于某些原因,GenericType修复程序不起作用。但是,由于类型擦除是针对集合而不是针对阵列完成的,所以这很有效。
@GET
@Produces(MediaType.APPLICATION_XML)
public Response getEvents(){
List<Event> events = eventService.getAll();
return Response.ok(events.toArray(new Event[events.size()])).build();
}
答案 2 :(得分:0)
我使用AsyncResponse的方法的解决方案
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void list(@Suspended
final AsyncResponse asyncResponse) {
asyncResponse.setTimeout(10, TimeUnit.SECONDS);
executorService.submit(() -> {
List<Product> res = super.listProducts();
Product[] arr = res.toArray(new Product[res.size()]);
asyncResponse.resume(arr);
});
}