John
John

Reputation: 1601

How to change JSON response format in the ResponseEntity?

I have some REST controller which generate a response to a user and send it.

  @RequestMapping(method = RequestMethod.GET, value = "/hello/contacts")
    public ResponseEntity<Page<ContactDto>> getContacts(@RequestParam(name = "nameFilter") String nameFilter
    , @RequestParam(name = "page", required = false, defaultValue = "1") int page
    , @RequestParam(name = "size", required = false, defaultValue = "100") int size) {

        List<ContactDto> contacts = contactService.getContacts(nameFilter);

        Pageable pagiable = PageRequest.of(page - 1, size);
        int start = (page - 1) * size;
        int end = start + size;

        Page<ContactDto> pages;
        if (end <= contacts.size()) {
            pages = new PageImpl<>(contacts.subList(start, end), pagiable, contacts.size());
            return new ResponseEntity<>(pages, HttpStatus.OK);
        } else {
            if (start < contacts.size()) {
                contacts.size();
                pages = new PageImpl<>(contacts.subList(start, contacts.size()), pagiable, contacts.size());
                return new ResponseEntity<>(pages, HttpStatus.OK);
            }
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

After sending response user get JSON response in next format:

{
    "content": [
        {
            "id": 1,
            "name": "Rm7W8bDq7z"
        },
        {
            "id": 2,
            "name": "vYYWLImOWe"
        },
        {
            "id": 3,
            "name": "gRKokZFEdf"
        }],``
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 100,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 10,
    "totalElements": 999,
    "last": false,
    "size": 100,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "numberOfElements": 100,
    "first": true,
    "empty": false
}

I want change JSON property name content to another name, for example, "contacts". How can I do this?

Upvotes: 1

Views: 1424

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

Generally you can't. Because the Page has content and it's not related to business. For Page it's neutral that what it contains.
But I think the below workaround can help.
You need to create a custom page class.

public class CustomPageImpl<T> extends PageImpl<T>{
@JsonProperty("contacts")
public List<T> getContent() {
  return super.getContent();
}
}

Then use this custom page class to return results.

Upvotes: 2

Related Questions