yve*_*lem 24 java json jaxb jersey generic-list
泽西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);
}
}
Run Code Online (Sandbox Code Playgroud)
但不能做同样的事情:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
给出错误: 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状态代码和标头.
yve*_*lem 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();
}
}
Run Code Online (Sandbox Code Playgroud)
客户端必须使用以下行来获取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>>() {
});
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,GenericType修复程序不起作用.但是,由于类型擦除是针对集合而不是针对阵列完成的,因此这很有用.
@GET
@Produces(MediaType.APPLICATION_XML)
public Response getEvents(){
List<Event> events = eventService.getAll();
return Response.ok(events.toArray(new Event[events.size()])).build();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25024 次 |
最近记录: |