Jersey puede producir la Lista pero no puede responder.ok(Lista.build()?


Jersey 1.6 puede producir:

@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);
    }
}

Pero no puede hacer lo mismo con:

@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();
    }
}

Dando el error: 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

Esto evita el uso de código de estado HTTP y encabezados.

Author: Timwi, 2011-05-21

3 answers

Es posible insertar un List<T> en una Respuesta de la siguiente manera:

@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();
    }
}

El cliente tiene que usar las siguientes líneas para obtener el 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>>() {
    });
}
 24
Author: yves amsellem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-21 12:26:56

Por alguna razón la solución GenericType no estaba funcionando conmigo. Sin embargo, dado que el borrado de tipos se realiza para Colecciones, pero no para matrices, esto funcionó.

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Response getEvents(){
        List<Event> events = eventService.getAll();
        return Response.ok(events.toArray(new Event[events.size()])).build();
    }
 8
Author: rodrigobartels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-31 22:02:16

Mi solución para métodos que usan 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
Author: Miguel Vieira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-20 15:24:09