Skip to content
Advertisement

How to return custom response in Spring with several attributes other than the List

I’m trying to get a custom response back from a spring rest controller back to the user, containing a list of all registered users and other keys such as sucess, etc. I tried the following approach but the Json array is completly escaped as a string…

JavaScript

I get something like this

JavaScript

and wanted something like:

JavaScript

Is there any way I can get the json array properly showed after a request?

Advertisement

Answer

You can let Spring Boot handle the serialization of the response entity.

Create a POJO which defines your response object.

JavaScript

This lets you simplify your getAllWorkers method a bit:

JavaScript

Note that I added a separate message field for the error message. I find that clients are much happier if a specific field is not used for different types of data. “info” should never be anything else than a list of workers and “message” should never be anything else than a String.

Disclaimer: I didn’t have a Spring Boot project setup to test this properly. If something is not working let me know and I will check it.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement