Jersey can produce List but cannot Response.ok(List).build()?

前端 未结 3 663
滥情空心
滥情空心 2020-12-24 02:45

Jersey 1.6 can produce:

@Path(\"/stock\")
public class StockResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List get()          


        
相关标签:
3条回答
  • 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();
        }
    }
    

    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>>() {
        });
    }
    
    0 讨论(0)
  • 2020-12-24 03:07

    my solution for methods that use 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);
        });
    }
    
    0 讨论(0)
  • 2020-12-24 03:10

    For some reason the GenericType fix wasn't working from me. However, since type erasure is done for Collections but not for Arrays, this worked.

        @GET
        @Produces(MediaType.APPLICATION_XML)
        public Response getEvents(){
            List<Event> events = eventService.getAll();
            return Response.ok(events.toArray(new Event[events.size()])).build();
        }
    
    0 讨论(0)
提交回复
热议问题