2017-09-13 53 views
2

我有一个使用jax-rs的web服务休息,我的服务返回一个对象列表,但是不知道如何将自定义状态值添加到响应中,例如 结果我想打造的是以下几点:如何使用消息返回响应,jax rs

如果其确定:

{ 
    "status": "success", 
    "message": "list ok!!", 
    "clients": [{ 
     "name": "john", 
     "age": 23 
    }, 
    { 
     "name": "john", 
     "age": 23 
    }] 
} 

如果是错误:

{ 
    "status": "error", 
    "message": "not found records", 
    "clients": [] 
} 

我休息服务:

@POST 
@Path("/getById") 
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(MediaType.APPLICATION_JSON) 
public List<Client> getById(Client id) { 

    try { 

     return Response.Ok(new ClientLogic().getById(id)).build(); 
     //how to add status = success, and message = list! ? 

    } catch (Exception ex) { 
     return ?? 
     // ex.getMessage() = "not found records" 
     //i want return json with satus = error and message from exception 
    } 
    } 

回答

0

我正面临同样的问题,这里是我如何解决它。 如果您的服务方法成功,请返回状态为200的响应以及所需的实体。如果你的服务方法抛出一个异常,返回具有不同状态的Response,并将异常消息绑定到你的RestError类。

@POST 
@Path("/getById") 
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(MediaType.APPLICATION_JSON) 
public Response getById(Client id) { 
    try {  
    return Response.Ok(new ClientLogic().getById(id)).build(); 
    } catch (Exception ex) { 
    return Response.status(201) // 200 means OK, I want something different 
        .entity(new RestError(status, msg)) 
        .build(); 
    } 
} 

在客户端,我使用这些实用方法从Response读取实体。如果有错误,我会抛出一个包含错误状态和msg的异常。

public class ResponseUtils { 

    public static <T> T convertToEntity(Response response, 
             Class<T> target) 
          throws RestResponseException { 
    if (response.getStatus() == 200) { 
     return response.readEntity(target); 
    } else { 
     RestError err = response.readEntity(RestError.class); 
     // my exception class 
     throw new RestResponseException(err); 
    } 
    } 

    // this method is for reading Set<> and List<> from Response 
    public static <T> T convertToGenericType(Response response, 
              GenericType<T> target) 
          throws RestResponseException { 
    if (response.getStatus() == 200) { 
     return response.readEntity(target); 
    } else { 
     RestDTOError err = response.readEntity(RestError.class); 
     // my exception class 
     throw new RestResponseException(err); 
    } 
    } 

} 

我的客户方法调用(通过代理对象)的服务方法

public List<Client> getById(Client id) 
         throws RestResponseException { 
    return ResponseUtils.convertToGenericType(getProxy().getById(id), 
              new GenericType<List<Client>>() {}); 
} 
2

如果你想在你的输出JSON结构的完全控制,使用JsonObjectBuilder(如解释here,那么你最终的JSON转换为字符串和写入(例如,对于成功的JSON):

return Response.Ok(jsonString,MediaType.APPLICATION_JSON).build(); 

并将您的返回值更改为Response对象。

但是请注意,您正在尝试发送冗余(而非标准)信息,该信息已编码为HTTP错误代码。当您使用Response.Ok时,响应的代码将为“200 OK”,并且您可以研究Response类方法以返回所需的任何HTTP代码。 在你的情况将是:

return Response.status(Response.Status.NOT_FOUND).entity(ex.getMessage()).build(); 

返回404 HTTP代码(看代码的Response.Status列表)。