I am designing a web service using Jersey and I need to add some custom fields to my JSON response always, similar to this:
{
"result": "0"/"Error code",
"message": "Message returned by server",
"custom_field": here goes string or class values required
}
For example, I have Token and User POJO classes:
public class Token {
private String token = null;
public Token (String token) {
this.token = token;
}
// getter and setter
}
public class User {
private String id= null;
private String name = null;
private String surname = null;
private String phone = null;
public User (String id, String name, String surname, String phone) {
this.id = id;
this.name = name;
this.surname = surname;
this.phone = phone;
}
// getters and setters
}
And this are login and getUser webservices:
@Path("/services")
@Produces(MediaType.APPLICATION_JSON)
public class HelloFromCxfRestService {
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Token login(String login, String password){
//Logic
return token;
}
@POST
@Path("/get_user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getUser (String id){
//Logic
return user; //in custom_field would be {"name":"myName", "surname":"mySurname", "phone":"myPhone"}
}
}
How can I return my custom JSON structure respecting POJOs? Obviously I should can put custom values in "result" and "message".