简体   繁体   中英

Java Spring Boot REST API **How to name the array of objects in HTTP json response?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM