1

私は、応答として JSON 文字列を返すサーバーへの残りの URL 呼び出しを行っているプロジェクトに取り組んでいます。サービスに問題がある場合は、エラー応答として以下の JSON 文字列のいずれかが返されます -

{"error":"no user_id passed"}

or

{"warning": "user_id not found", "user_id": some_user_id}

or

{"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition}

or

{"error":"no client_id passed"}

or

{"error": "missing client id", "client_id":2000}

しかし、それが成功の応答である場合、json文字列が次のように返されます-

{"@data": {"oo":"1205000384","p":"2047935"} 

以下は、私が呼び出しを行っているコードですresponse。サービス側で何か問題が発生した場合、または成功した場合、変数は上記の JSON 文字列になります。

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);

// here response has the JSON string

ClientResponse clientResponse = checkJSONResponse(response);

return clientResponse;

現在、何もチェックせずにそのままレスポンスを返しています。しかし今、私は応答を確認し、それがエラーであるかどうかを確認し、特定のエラーでログに記録し、それが成功応答である場合はそれを返すことを考えています.

最初のオプション:-response呼び出しごとに毎回上記のjson文字列を逆シリアル化し、成功またはエラー応答があるかどうかを確認する必要があります。

2番目のオプション:-または、応答文字列がエラーまたは警告で始まっているかどうかを確認し、エラーまたは警告で始まっている場合は、応答を逆シリアル化し、特定のエラー メッセージを抽出する必要があります。

ほとんどの場合、データが返されて成功の応答が返され、約2%しかエラー応答が返されないため、エラーケースのみを抽出するためだけに毎回逆シリアル化すると、startsWithエラーや警告に比べて費用がかかると考えていますオプションを選択してからデシリアライズしますか?

最初のオプション-

private ClientResponse checkJSONResponse(final String response) throws Exception {

Gson gson = new Gson();
ClientResponse clientResponse = null;
JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse
if (jsonObject.has("error") || jsonObject.has("warning")) {

    final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
        .get("warning").getAsString();

    // log error here
    ClientResponse clientResponse = new ClientResponse(response, "ERROR_OCCURED", "SUCCESS");
} else {
    ClientResponse clientResponse = new ClientResponse(response, "NONE", "SUCCESS");
}

    return clientResponse;
}

2番目のオプション-

private ClientResponse checkJSONResponse(final String response) throws Exception {

Gson gson = new Gson();
ClientResponse clientResponse = null;
if(response.startsWith("{\"error\":") || response.startsWith("{\"warning\":")) {
    JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse
    if (jsonObject.has("error") || jsonObject.has("warning")) {

        final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
            .get("warning").getAsString();

        // log error here with specific messages
        ClientResponse clientResponse = new ClientResponse(response, "ERROR_OCCURED", "SUCCESS");
    }
} else {
        ClientResponse clientResponse = new ClientResponse(response, "NONE", "SUCCESS");
    }

    return clientResponse;
}

私のユースケースに最適なオプションは何ですか? 私は主にパフォーマンスの観点からどのオプションがより効率的かを見ていますか?

4

1 に答える 1