【发布时间】:2017-12-22 16:48:21
【问题描述】:
我开发了一个 spring boot 应用程序,在控制器中我有一个返回产品列表的方法
@GetMapping
public ResponseEntity<List<Product>> listAllProducts() {
List<Product> products = productRepository.findAll();
if (products.isEmpty()) {
return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Product>>(products, HttpStatus.OK);
}
结果如下:
[
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
},
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
},
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
}
]
如何修改方法 listAllProducts 以使结果如下所示
{
"products": [
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
},
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
},
{
"name": "Ruby on Rails Baseball Jersey",
"description": null,
"price": 19.99,
"slug": "ruby-on-rails-tote"
}
]
}
【问题讨论】:
-
能否将 ResponseEntity
- > 更改为 ResponseEntity
并使 List 成为 MyProductList 的成员?
标签: json spring spring-boot spring-rest