Ragnar
Ragnar

Reputation: 21

Custom JSON response with Spring Boot

I developed a spring boot application, in the controller i have a method that returns a list of products

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

the result is as follows:

[
{
    "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"
}
]

How can i modify the method listAllProducts so that the result comes like this

{
"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"
    }
]
}

Upvotes: 1

Views: 8603

Answers (2)

rajeshnair
rajeshnair

Reputation: 1673

Create a model class

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

and modify your ResponseEntity to return Products instead of List

   public ResponseEntity<Products> listAllProducts()

This should solve it for you

Upvotes: 0

lzagkaretos
lzagkaretos

Reputation: 2910

A simple way of doing this is by using a ProductListDto containing List<Product>.

public class ProductListDto {       
    private List<Product> products;     
    public ProductListDto() {}      
    public ProductListDto(List<Product> products) {
        this.products = products;
    }       
}    

And then:

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

Upvotes: 5

Related Questions