Android 如何检查来自服务器的响应是JSONAobject还是JSONArray?
可能重复:Android 如何检查来自服务器的响应是JSONAobject还是JSONArray?,android,json,Android,Json,可能重复: 默认情况下,我有一个返回一些JSONArray的服务器,但当出现错误时,它会返回带有错误代码的JSONObject。我试图解析json并检查错误,我有一段代码检查错误: public static boolean checkForError(String jsonResponse) { boolean status = false; try { JSONObject json = new JSONObject(jsonResponse);
默认情况下,我有一个返回一些JSONArray的服务器,但当出现错误时,它会返回带有错误代码的JSONObject。我试图解析json并检查错误,我有一段代码检查错误:
public static boolean checkForError(String jsonResponse) {
boolean status = false;
try {
JSONObject json = new JSONObject(jsonResponse);
if (json instanceof JSONObject) {
if(json.has("code")){
int code = json.optInt("code");
if(code==99){
status = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status ;
}
但是当jsonResponse正常并且是JSONArray(JSONArray无法转换为JSONOBject)时,我会得到JSONException。如何检查jsonResponse是否会为我提供JSONArray或JSONOBject?您正在尝试将从服务器获得的字符串响应转换为引起异常的
JSONOBject
。正如您所说,您将从服务器获得JSONArray
,您尝试将其转换为JSONArray
。请参阅此文档,它将帮助您将字符串响应转换为JSONObject
和JSONArray
。如果响应以[(开方括号)开头,则将其转换为JsonArray,如下所示
JSONArray ja = new JSONArray(jsonResponse);
如果您的响应以{(开放式花括号)开头,则将其转换为
JSONObject jo = new JSONObject(jsonResponse);
使用。将为您提供一个对象
,该对象可以根据实例动态转换为适当的类型
Object json = new JSONTokener(jsonResponse).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
//further actions on jsonObjects
//...
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
//further actions on jsonArray
//...
}