【问题标题】:How to check if response from server is JSONAobject or JSONArray? [duplicate]如何检查来自服务器的响应是 JSONAobject 还是 JSONArray? [复制]
【发布时间】:2013-01-19 02:17:51
【问题描述】:

可能重复:
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?

【问题讨论】:

    标签: android json


    【解决方案1】:

    使用JSONTokenerJSONTokener.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
        //...
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试将您从服务器获得的转换字符串响应转换为导致异常的JSONObject。正如您所说,您将从服务器获得JSONArray,您尝试转换为JSONArray。请参考此link,它将帮助您何时将字符串响应转换为JSONObjectJSONArray。如果您的响应以 [(开方括号)开头,则将其转换为 JsonArray,如下所示

      JSONArray ja = new JSONArray(jsonResponse);
      

      如果您的响应以 {(开花括号)开头,则将其转换为

      JSONObject jo = new JSONObject(jsonResponse);
      

      【讨论】:

        猜你喜欢
        • 2012-10-19
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 2013-04-06
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多