如何检查来自服务器的响应是JSONAobject还是JSONArray? [英] How to check if response from server is JSONAobject or JSONArray?

查看:82
本文介绍了如何检查来自服务器的响应是JSONAobject还是JSONArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
确定JSON是JSONObject还是JSONArray

Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray

我有一个服务器,默认情况下会返回一些JSONArray,但是当发生错误时,它将返回带有错误代码的JSONObject.我正在尝试解析json并检查错误,我有一段代码可以检查错误:

I have a server that returns some JSONArray by default, but when some error occurs it returns me JSONObject with error code. I'm trying to parse json and check for errors, I have piece of code that checks for error:

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时我得到JSONException(无法将JSONArray转换为JSONOBject)如何检查jsonResponse是否将为我提供JSONArray或JSONObject?

but I get JSONException when jsonResponse is ok and it's a JSONArray (JSONArray cannot be converted to JSONOBject)How to check if jsonResponse will provide me with JSONArray or JSONObject ?

推荐答案

使用 JSONTokener . JSONTokener.nextValue() 将为您提供Object可以根据实例动态转换为适当的类型.

Use JSONTokener. The JSONTokener.nextValue() will give you an Object that can be dynamically cast to the appropriate type depending on the instance.

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

这篇关于如何检查来自服务器的响应是JSONAobject还是JSONArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆