泽西岛自定义JSON响应

时间:2015-08-24 11:38:52

标签: java json jersey jersey-client

我正在使用Jersey设计一个Web服务,我需要总是在我的JSON响应中添加一些自定义字段,类似于:

{
    "result": "0"/"Error code",
    "message": "Message returned by server",
    "custom_field": here goes string or class values required
}

例如,我有令牌和用户POJO类:

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
}

这是login和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"}
    }
}

如何返回关于POJO的自定义JSON结构?显然我应该把自定义值放在"结果"和"消息"。

2 个答案:

答案 0 :(得分:4)

创建Response类:

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
}

然后在控制器中:

@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);
}

答案 1 :(得分:1)

在客户端,您可以使用以下代码:

 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;
}
}