简体   繁体   中英

Jersey custom JSON responses

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".

Create Response class:

public class Response<T> {
    String result;
    String message;
    T customField;

    public Response(String result, String message, T customField) {
        this.result = result;
        this.message = message;
        this.customField = customField;
    }
    //getter setter
}

and then in controller:

@POST
@Path("/get_user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response<User> getUser (String id){
    //Logic
    return new Response<User> ("result", "message", user);
}

in client side you can use following code:

 public class WSClient {
   private URI uri;
   private Client client;

   public WSClient(){
   uri = UriBuilder.fromUri("pathToYoutWebservice").port(8080).build();
   client = ClientBuilder.newClient();
}

 public User getUser(String userId){

 User user = client.target(uri).path(java.text.MessageFormat.format("{0}", new Object[]{userId})).request(MediaType.APPLICATION_JSON).get(User.class);
 return user;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM