简体   繁体   中英

Spring data rest: Can we rename the “content” property in pagination result?

I have an endpoint which gives the results as paginated output like below.

Code Snippet:

public Page<MyObject> getData(Pageable pageable) {
    return repository.findAll(pageable);
}

Response:

{
    "content": [
        {
            "id": 2,
            "name": "",
            "regionName": "",
            "category1": "",
            "category2": "",
            "modifiedDateTime": "",
            "abstract": ""
        }
    ],
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true
        },
        "offset": 0,
        "pageSize": 1,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "last": false,
    "totalPages": 10,
    "totalElements": 5808,
    "size": 1,
    "number": 0,
    "numberOfElements": 1,
    "first": true,
    "sort": {
        "sorted": false,
        "unsorted": true
    }
}

Can we rename the property name "content" to a different name like "data"?

Also Can we remove the additional paging parameters in the output? For eg: sort, offset

You can't modify PageImpl class and add @JsonProperty s to rename but you can create a decorator for it. Also if you need to hide pageable (or any other properties) then you just don't expose them to decorator.

class PageDecorator<T> {

    private final Page<T> page;

    public PageDecorator(Page<T> page) {
        this.page = page;
    }

    @JsonProperty("data") // override property name in json
    public List<T> getContent() {
        return this.page.getContent();
    }

    public int getTotalPages() {
        return page.getTotalPages();
    }

    public long getTotalElements() {
        return page.getTotalElements();
    }

    ... 
}

Your code shall look like:

public PageDecorator<MyObject> getData(Pageable pageable) {
    return new PageDecorator<>(repository.findAll(pageable));
}

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