【问题标题】:Custom JSON response with Spring Boot使用 Spring Boot 自定义 JSON 响应
【发布时间】: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


【解决方案1】:

一种简单的方法是使用包含List&lt;Product&gt; 的ProductListDto。

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

【讨论】:

  • @aymenkn,如果 findAll() 给出一个空列表,我会返回 HttpStatus.OK 和一个空列表。
【解决方案2】:

创建模型类

public class Products {
    private List<Product> products = null;
}

并修改您的 ResponseEntity 以返回 Products 而不是 List

   public ResponseEntity<Products> listAllProducts()

这应该会为你解决问题

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多