Home > Blockchain >  Spring Boot - Returning JSON with map of list of object and another object
Spring Boot - Returning JSON with map of list of object and another object

Time:05-03

I made a RestController for bulletin board application. Firstly, I made a simple version without pagination logic as follows.

Request URL is:

    http://localhost:8005/article => show article list(List<ArticleDto>)

I can make json response like this

    public ResponseEntity<List<ArticleDto>> articleList(){
        List<ArticleDto> list = articleService.list();
        return new ResponseEntity<List<ArticleDto>>(list, HttpStatus.OK);
    }

and I got this json.

[{"articleId":1, "title": "...", "content": "..."},
{"articleId":1, "title": "...", "content": "..."},
{"articleId":1, "title": "...", "content": "..."}, ...]

It is a really long list, so, I want to make a more complex version with pagenation info. But, I don't know how to make a json response with both article list and pagenation info because my response type is ResponseEntity<List<ArticleDto>>.

Request URL is:

    http://localhost:8005/article?currentPage=1 => show 10 articles of first page(List<ArticleDto>) with pagenation(Pagination object).
public ?? articleList(@RequestParam(value="currentPage", required=false) String currentPage) throws Exception {

        int itemsPerPage = 10;
        int pagesPerGroup = 10;
        if (currentPage == null || currentPage == "") currentPage = "1";

        Map<String, String> map = new HashMap<String, String>();
        map.put("currentPage", currentPage);

        int totalItemCount = articleService.totalItemCount(map);
        Pagination pagination = new Pagination(totalItemCount, itemsPerPage, pagesPerGroup, Integer.parseInt(currentPage));

        map.put("offset", "" pagination.getOffset());
        map.put("limit", "" pagination.getLimit());
        
        List<ArticleDto> list = articleService.list(map);
        
        
        return new ?? ( ?? , HttpStatus.OK);
    }

I want to get a json return like this:

{
  "articles": [{"articleId": 1, "title": "...", "content": "..."} ...],
  "pagination": {
    "currentPage": 1,
    "totalItemCount": 121,
    "itemsPerPage: 10,
    "lastPage": 13,
    ...
  }
}

I can do it very easily when I use express or laravel, but it is really hard in Java. I am new to Java, please help me.

CodePudding user response:

Use a class to encapsulate the response.

class ArticleResponse{
  List<ArticleDto> articles;
  Pagination pagination;
}

Populate these values and then send the object back.

CodePudding user response:

Spring Data JPA already provides an interface for Pagination.

You can read the documentation or review the javadocs.

  • Related