Reputation: 324
This may be dumb question but I am unable to find the answer while looking through documentation for java REST API. My question is that I want to name the REST array JSON api response and format it with a name.
for example below is the response from my REST API being pulled from my backend.
current API response
[
{
"categoryName": "Hardware",
"categoryId": 1
},
{
"categoryName": "Software",
"categoryId": 2
}
]
desired API response
"categories": [
{
"categoryName": "Hardware",
"categoryId": 1
},
{
"categoryName": "Software",
"categoryId": 2
}
]
controller
@RequestMapping(method = RequestMethod.GET,)
@ResponseBody
public List<Category>findAllCategories() {
return categoryRepository.findAll();
}
model
private String categoryName;
private int categoryId;
**getters/setters**
Upvotes: 1
Views: 1217
Reputation: 571
You would need to do it like this:
@RequestMapping(method = RequestMethod.GET,)
@ResponseBody
public CategoriesResponse findAllCategories() {
return new CategoriesResponse(categoryRepository.findAll());
}
private class CategoriesResponse() {
private List<Category> categories;
CategoriesResponse(List<Category> categories) {
this.categories = categories;
}
/* getters and setters */
}
You can use JSON to POJO converters like this to convert a JSON into Java classes if you have any doubts. The other option is to build your own serializer, but that may be an overkill for a case like this.
Upvotes: 2
Reputation: 174
hello what you should do is the following
create a vo class
private String categoryName;
private int categoryId;
**getters/setters**
and another that contains a list of the previous vo
private List<Vo> categories;
**getters/setters**
Upvotes: 0