且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jersey 可以产生 List<T>但不能 Response.ok(List<T>).build()?

更新时间:2023-09-26 18:38:22

可以通过以下方式在响应中嵌入 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>>() {
    });
}