[英]How to check response from the RestTemplate for error and success case for the JSON String?
我正在做一个项目,在这个项目中我对服务器进行了REST 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}
以下是我进行调用的代码,如果服务端出现问题,则response
变量将在JSON字符串上方,但如果响应成功,则将不包含上述任何JSON字符串。 这将是具有适当数据的有效JSON字符串,但成功响应的JSON字符串与上述错误情况JSON字符串相比完全不同,因此我无法为此使用相同的POJO。
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
// check response here as it will have above error JSON String if
// something has gone wrong on the server side, and some other data if it is a success
如果响应包含上述任何JSON字符串,那么我需要记录一个错误,因为它是一个错误,但是如果响应中不包含上述JSON字符串,则记录为成功。
注意:如果来自服务的响应不成功,则将错误和警告作为JSON字符串中的第一个键。但是,如果成功,则将正确处理JSON字符串中的数据。
解决此问题的最简单有效的方法是什么?
如果成功返回其他响应且不包含键“错误”,则此方法有效。
JSONObject jsonObject = new JSONObject(response);
bool isError = false;
//I checke for one error you can do same for other errors and warning as well. You can directly check this from array.
if(jsonObject.has("error"))
{
String error = jsonObject.getString("error");
if(errror == "no user_id passed")
{
isError = true;
}
}
if(!isError)
{
//continue what you were doing.
}
您可以使用org.json库中的JSONObject的“ has”方法来检查json字符串中是否存在特定密钥。 您可以使用此方法检查服务器是否返回错误并进行相应处理。
示例代码:
//Array of all errors
String[] error_list = ["no user_id passed","user_id not found","user_id for wrong partition","no client_id passed"];
public boolean isErrorResp(String json_response)
{
try
{
JSONObject json_obj = new JSONObject(json_response); //create JSONObject for your response
//check if your response has "error" key if so check if the value of error key is in the error_list array
if(json_obj.has("error")&&Arrays.asList(error_list).contains(json_obj.getString("error")))
{
return true;
}
else if(json_obj.has("warning")&&Arrays.asList(error_list).contains(json_obj.getString("warning")))
{
return true;
};
return false;
}
catch(JSONException ex)
{
//error handling for improper json string.
return false;
}
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.