[英]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.