泽西岛可以生成List<T>但不能Responser.ok(List<T>).build()?

2022-09-01 20:53:54

泽西岛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 状态代码和标头。


答案 1

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

答案 2

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

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