2017-09-13 7 views
2

私はjax-rsを使用してWebサービスを休息しています。私のサービスはオブジェクトのリストを返しますが、結果にカスタムステータス値を追加する方法はわかりません。例えば、 私が構築したいことは以下の通りです:返信方法返信するメッセージ、jax rs

もしそのOK:

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

私のRESTサービス:

エラーです

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

場合

@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のレスポンスと必要なエンティティを返します。サービスメソッドが例外をスローした場合は、レスポンスを別のステータスで返し、例外メッセージを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の構造上の完全な制御をしたい場合は、hereが説明したように、あなたの最終的なJSONを文字列に変換し、()成功JSONのための例のために書く、(JsonObjectBuilderを使用します。

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

戻り値をResponseオブジェクトに変更します。

ただし、すでにHTTPエラーコードにエンコードされている冗長(標準ではない)情報を送信しようとしていることに注意してください。 Response.Okを使用すると、レスポンスコードは「200 OK」になり、希望のHTTPコードを返すためのクラスメソッドResponseを調べることができます。 あなたのケースでは、それは次のようになります。404 HTTPコードを返す

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

(コードのResponse.Statusリストを見てください)。

関連する問題