Search code examples
springspring-bootspring-restcontroller

How to add the result from a RestController to a custom wrapper object in Spring


Our front end application always expects a certain json format for the result, something like:

{
success: true,
errors: [],
responseObject: ...
}

Say I want to return a list of users, that list would be a in the responseObject. Now I would like to be able to just return this list from the restcontroller and have something like a controller advice wrap the list in this response object. However as I understand I cannot use the controller advice in this case. Is there a way to do this?


Solution

  • You can use for this purpose Filter. You can get your list of users from the response object, wrap in your desired model structure and change in response.

    Example: https://medium.com/@sportans300/fiddling-with-httpresponses-in-java-2a269cd5a474