Issue
I would like to return a custom message along with data that my endpoint is supposed to return in json
format. E.g:
{
"id": "1",
"name": "John",
"surname": "Jackson",
"city": "Los Angeles"
"message": "There was only 1 person in chosen category"
}
So my POJO class of person
has fields: id
, name
, surname
, city
. However I would like to return message too, so the client application can display the message on the front-end. I was looking for a solution. By default Controller
endpoint can return the object as json
no problem. But that just gives me data, 200
status and that's it. I found about returning ResponseEntity
, but this doesn't solve the problem either since in response body it takes a POJO so I still can't send a custom message along with data. I need to send custom message, data and a proper status code.
Solution
You can create a generic class that you will return from your controllers which will enrich your models with message
property :
public class ServerResponse {
@JsonUnwrapped
private final Object wrapped;
private final String message;
public ServerResponse(Object wrapped, String message) {
this.wrapped = wrapped;
this.message = message;
}
//getters
}
and then you can pass any object to this class in the constructor and let Jackson handle the serialization for you. This way you do not have to create a new class per your model :
User user = new User("1", "John", "Jackson", "Los Angeles");
ServerResponse serverResponse = new ServerResponse(user, "There was only 1 person in chosen category");
and when you return ServerResponse
from the controller it will be serialized to :
{
"id":"1",
"name":"John",
"surname":"Jackson",
"city":"Los Angeles",
"message":"message"
}
Answered By - Michał Krzywański
Answer Checked By - David Marino (JavaFixing Volunteer)