我开发了一个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"
}
]
}
一个简单的方法是使用包含ProductListDto
的List<Product>
。
public class ProductListDto {
private List<Product> products;
public ProductListDto() {}
public ProductListDto(List<Product> products) {
this.products = products;
}
}
然后:
@GetMapping
public ResponseEntity<ProductListDto> listAllProducts() {
List<Product> products = productRepository.findAll();
if (products.isEmpty()) {
return new ResponseEntity<ProductListDto>(HttpStatus.NO_CONTENT);
}
ProductListDto productListDto = new ProductListDto(products);
return new ResponseEntity<ProductListDto>(productListDto, HttpStatus.OK);
}
创建一个模型类
public class Products {
private List<Product> products = null;
}
并修改您的ResponseEntity以返回Products而不是List
public ResponseEntity<Products> listAllProducts()
这应该为你解决