如何在JSON字符串中检查给定对象是对象还是数组 [英] How to check whether the given object is object or Array in JSON string

查看:168
本文介绍了如何在JSON字符串中检查给定对象是对象还是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网站获取JSON字符串。我的数据看起来像这样(JSON数组)

I am getting JSON string from website. I have data which looks like this (JSON Array)

 myconf= {URL:[blah,blah]}

但有时这些数据可以是(JSON对象)

but some times this data can be (JSON object)

 myconf= {URL:{try}}

也是可以为空

 myconf= {}    

我希望在其对象时执行不同的操作,而在其数组时则不同。直到我的代码,我试图只考虑数组,所以我得到以下异常。但我无法检查对象或数组。

I want to do different operations when its object and different when its an array. Till now in my code I was trying to consider only arrays so I am getting following exception. But I am not able to check for objects or arrays.

我遇到异常

    org.json.JSONException: JSONObject["URL"] is not a JSONArray.

任何人都可以建议如何修复它。在这里,我知道对象和数组是JSON对象的实例。但我找不到一个函数,我可以用它来检查给定的实例是一个数组还是一个对象。

Can anyone suggest how it can be fixed. Here I know that objects and arrays are the instances of the JSON object. But I couldn't find a function with which I can check whether the given instance is a array or object.

我试过使用这个if条件但没有成功

I have tried using this if condition but with no success

if ( myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0)


推荐答案

JSON对象和数组分别是 JSONObject JSONArray 的实例。除此之外, JSONObject 有一个 get 方法,它会返回一个对象,你可以检查自己的类型不用担心ClassCastExceptions,而且还有。

JSON objects and arrays are instances of JSONObject and JSONArray, respectively. Add to that the fact that JSONObject has a get method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.

if (!json.isNull("URL"))
{
    // Note, not `getJSONArray` or any of that.
    // This will give us whatever's at "URL", regardless of its type.
    Object item = json.get("URL"); 

    // `instanceof` tells us whether the object can be cast to a specific type
    if (item instanceof JSONArray)
    {
        // it's an array
        JSONArray urlArray = (JSONArray) item;
        // do all kinds of JSONArray'ish things with urlArray
    }
    else
    {
        // if you know it's either an array or an object, then it's an object
        JSONObject urlObject = (JSONObject) item;
        // do objecty stuff with urlObject
    }
}
else
{
    // URL is null/undefined
    // oh noes
}

这篇关于如何在JSON字符串中检查给定对象是对象还是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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