Returning a message for the client in json format along with data - Java/Spring/REST

T4under4 :

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.

Tigran :

Try to create new helper class(CustomUser) that have id, name, surname, city, message fields(getters and setters). And on sending you the user(new User with properties) on your controller, create new Instance of CustomUser class, set properties, and send customUser, Like this:

CustomUser customUser = new CustomUser();
customUser.setId(user.getId);
customUser.setName(user.getName);
customUser.setSurname(user.getSurname);
customUser.setCity(user.getCity);
customUser.setMessage("Custom message");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403467&siteId=1