java - 如何检查给定对象是JSON字符串中的对象还是数组

标签 java getjson json

我正在从网站获取 JSON 字符串。我有这样的数据(JSON 数组)

 myconf= {URL:[blah,blah]}

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

 myconf= {URL:{try}}

也可以为空

 myconf= {}    

我想在它的对象上做不同的操作,而在它的数组上做不同的操作。到目前为止,在我的代码中,我试图只考虑数组,所以我遇到了以下异常。但我无法检查对象或数组。

我遇到异常

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

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

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

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

最佳答案

JSON 对象和数组分别是JSONObjectJSONArray 的实例。除此之外,JSONObject 有一个 get 方法,它会返回一个对象,您可以检查自己的类型,而不必担心 ClassCastExceptions,就这样吧。

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
}

关于java - 如何检查给定对象是JSON字符串中的对象还是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9817315/

相关文章:

java - spinner.setAdapter() 中的 NullPointerException

javascript - 这个 getJson 调用有什么问题

java - 如何在 Android/Java 中获取 wunderground API 的 Json 元素

java - 使用 Jackson 将 Json 数组映射到 POJO

javascript - 浏览器原生 JSON 支持 (window.JSON)

java - 编写结合使用接口(interface)和单独类的 Java 方法

java - 带有 session 对象的 Spring Junit - 在 Controller 中不可见

java - Windows 和 OS X 桌面应用程序的首选开发平台

json - 如何设置正确的 json header ?

javascript - 为什么多个 $.getJSON 调用不能正常工作?