如何检查服务器中的响应是JSONAobject还是JSONArray?

程序中的一个服务器,默认返回一些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 可以运行时确获得 JSONException。它是一个JSONArray,JSONArray
不能转换成 JSONOBject。如何确认 jsonResponse 传过来的值是 JSONArray 还是 JSONObject ?

我明白你的意思了,首先看下这两个类型转换为字符串后的区别

    ......
    JSONObject jo = createJSONObject();    
    JSONArray ja = new JSONArray();
    ja.put(jo);        
    System.out.println("jo is "+jo.toString());//{"sex":"男","username":"ZhangSam","score":123}
    System.out.println("ja is "+ja.toString());//[{"sex":"男","username":"ZhangSam","score":123}]      
}
public static JSONObject createJSONObject(){
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("username", "ZhangSam");     
        jsonObject.put("sex", "男");
        jsonObject.put("score", new Integer(123));          
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonObject;
}

所以你要想写都能识别的,只需正则检查是否[开头即可
然后才能进行你的这一步:如是非[开头,JSONObject json = new JSONObject(jsonResponse);
另外还一种方法就是在finally中处理
最后一点与题无关的是,JSONObject与JSONArray可以互转,
(toJSONObject/toJSONArray)

使用 JSONTokener。
JSONTokener.nextValue()会给出一个对象,然后可以动态的转换为适当的类型。

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