'Reformat payload data from mysql database
I have a database that looks like this on MySQL Workbench: [mysql][1] [1]: https://i.stack.imgur.com/WQmTp.png
I created an endpoint in Spring that returns all records from above database:
@RequestMapping("/api/v1/")
public class ProductController {
@Autowired
private ProductRepository productRepository;
// get all products
@GetMapping("/products")
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
Currently the endpoint returns JSON in this format:
[
{
"id": 1,
"name": "Brown Brim",
"price": 25,
"title": "Hats"
},
...
{
"id": 9,
"name": "Adidas NMD",
"price": 220,
"title": "Sneakers"
},
...
]
Just an array with all the data.
Is there a way to format it like this with a Java function?:
[
Hats: {"id":1, "name": "Brown Brim", "price":25},{... another product that is a hat},
Sneakers: {"id":9, "name": "Adidas NMD", "price": 220},{... more sneakers}
]
I want it to create an array of objects, where the object is identified by the "title" field and has the rest of values in an object inside.
Or do I need to change the database itself?
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|