[英]How to use regular expressions to identify the error message in the JSON String?
我正在一個項目中,在該項目中,我正在使用RestTemplate
調用我的一台服務器,該服務器正在運行一個寧靜的服務並從中獲取響應。
如果出了問題,我將從服務器獲得的響應可以是這些錯誤響應中的任何一個(這就是我對錯誤響應的全部響應)-
{"warning": "user_id not found", "user_id": some_user_id}
{"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition}
{"error": "missing client id", "client_id":2000}
或低於成功的響應(可以是任何隨機json字符串鍵,也可以不同)-
{"@data": {"oo":"1205000384","p":"2047935"}
error
或warning
,例如我到達服務器的前面,例如user_id not found
或missing client id
。 在我的用例中,如果它是成功的響應,則不需要反序列化我的響應字符串,因為我們對此沒有任何POJO,並且將返回從服務器獲得的響應字符串。 但是只是為了記錄特定的錯誤消息(如果我從服務器獲取錯誤響應),我正在反序列化它,我認為這是不必要的。 對於我的用例,可能會有更好的解決方案。
下面是我的Java客戶端,它使用future.get
調用Callable
任務-
public class TestingClient implements IClient {
private ExecutorService service = Executors.newFixedThreadPool(10);
private RestTemplate restTemplate = new RestTemplate();
@Override
public String executeSync(ClientKey keys) {
String response = null;
try {
ClientTask ClientTask = new ClientTask(keys, restTemplate);
Future<String> future = service.submit(ClientTask);
response = handle.get(keys.getTimeout(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
} catch (Exception e) {
}
return response;
}
}
現在下面是我的ClientTask
類,該類實現Callable接口。 在call方法中,我生成一個URL,然后使用RestTemplate
命中服務器並返回響應-
class ClientTask implements Callable<String> {
private ClientKey cKeys;
private RestTemplate restTemplate;
public ClientTask(ClientKey cKeys, RestTemplate restTemplate) {
this.restTemplate = restTemplate;
this.cKeys = cKeys;
}
@Override
public String call() throws Exception {
// .. some code here
String url = "some_url";
String response = restTemplate.getForObject(url, String.class);
String test = checkJSONResponse(response);
return test;
}
private String checkJSONResponse(final String response) throws Exception {
// may be there are some better way of doing it for my scenario instead of using GSON
Gson gson = new Gson();
String str = null;
JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse it, may be performance issues here/
if (jsonObject.has("error") || jsonObject.has("warning")) {
final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
.get("warning").getAsString();
// log specific `error` here using log4j
str = response;
} else {
str = response;
}
return str;
}
}
如您在上面的代碼中看到的,如果我們得到任何錯誤響應,我們將反序列化JSON字符串僅記錄特定的錯誤消息。 但是對於成功的響應,我們不需要任何反序列化,但是我們仍在這樣做。
有解決這個問題的更好方法嗎? 因為當前我看到GSON反序列化的一些性能問題。
我可以識別成功響應和錯誤響應的唯一方法是響應中包含error
或warning
,因此我考慮使用正則表達式將錯誤或警告標識為響應字符串中的鍵。 如果它們在響應字符串中包含錯誤或警告,則提取特定的錯誤或警告消息並記錄下來。
我想可能有一些更好的方法可以解決此問題,而不必付出反序列化的費用。
我認為僅僅依靠正則表達式是很危險的。 如果服務器稍微更改輸出格式怎么辦?
我將嘗試進行快速測試,可能使用簡單的正則表達式來查找字符串"error"
並且如果有可能是錯誤響應,請進行完全反序列化以確定是否確實是錯誤。
當常規響應偶然觸發快速檢查時,您只需為誤報支付額外費用。
我將使用http代碼來控制成功/失敗數據解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.