2017-09-13 51 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列表)。