如何检查服务器的响应是 JSONAobject 还是 JSONArray? [复制]

2024-04-16

可能的重复:
确定 JSON 是 JSONObject 还是 JSONArray https://stackoverflow.com/questions/6118708/determine-whether-json-is-a-jsonobject-or-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 正常并且它是 JSONArray (JSONArray 无法转换为 JSONOBject)时,我得到 JSONException 如何检查 jsonResponse 是否会为我提供 JSONArray 或 JSONObject ?


Use JSONTokener http://developer.android.com/reference/org/json/JSONTokener.html. The JSONTokener.nextValue() http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()会给你一个Object可以根据实例动态转换为适当的类型。

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
    //...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查服务器的响应是 JSONAobject 还是 JSONArray? [复制] 的相关文章

随机推荐