Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何检查来自服务器的响应是JSONAobject还是JSONArray?_Android_Json - Fatal编程技术网

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
    //...
}