我正在开发一个项目,其中我对我的服务器进行剩余 URL 调用,该调用返回一个 JSON 字符串作为响应。如果服务有任何问题,那么它会给我以下 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;
目前我正在返回响应,但没有检查任何内容。但现在我正在考虑验证响应并查看它是否是错误,然后记录特定错误,如果是成功响应,则返回它。
第一个选项:- 那么我应该每次调用时反序列化上面的 json response
字符串,然后查看它是否有成功或错误响应。
第二个选项:- 或者我应该检查响应字符串是否以错误或警告开头,如果以错误或警告开头,则反序列化响应并提取特定的错误消息。
因为大多数时候我们都会得到成功响应并返回数据,只有大约 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;
}
第二个选项-
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;
}
对于我的用例来说,最好的选择是什么?我主要是从性能的角度来看哪个选项会更有效?
最佳答案
第一个显然更好。你所做的事情叫做premature optimization 。第二种情况很容易出错,想象一下如果元素重新排序会发生什么。在确定这是一个瓶颈之前,不要进行优化。
UPD:如果您分析了代码并发现无用的对象解析确实是一个问题。您可以分配错误代码,而不是传递字符串值,并使用 lastIndexOf()
方法而不是 startsWith()
。这将防止您遇到对象重新排序问题,但会保证警告消息中不会出现“错误”一词。
关于java - startswith vs JSON 反序列化性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21328122/