1

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**

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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**

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.