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

Jud*_*udy 16 java json getjson

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

 myconf= {URL:[blah,blah]}
Run Code Online (Sandbox Code Playgroud)

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

 myconf= {URL:{try}}
Run Code Online (Sandbox Code Playgroud)

也可以是空的

 myconf= {}    
Run Code Online (Sandbox Code Playgroud)

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

我得到以下异常

    org.json.JSONException: JSONObject["URL"] is not a JSONArray.
Run Code Online (Sandbox Code Playgroud)

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

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

if ( myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0)
Run Code Online (Sandbox Code Playgroud)

cHa*_*Hao 39

JSON对象和数组分别是JSONObject和的实例JSONArray.除此之外,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
}
Run Code Online (Sandbox Code Playgroud)


Oh *_*oon 7

有很多方法.

如果您担心系统资源问题/滥用Java异常来确定数组或对象,则不建议使用此方法.

try{
 // codes to get JSON object
} catch (JSONException e){
 // codes to get JSON array
}
Run Code Online (Sandbox Code Playgroud)

要么

这是推荐的.

if (json instanceof Array) {
    // get JSON array
} else {
    // get JSON object
}
Run Code Online (Sandbox Code Playgroud)


小智 7

我也遇到了同样的问题。不过,我已经以一种简单的方式修复了。

我的json如下所示:

[{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}]
Run Code Online (Sandbox Code Playgroud)

有时,我得到这样的回应:

{"id":7, "excerpt":"excerpt here"}
Run Code Online (Sandbox Code Playgroud)

我也和你一样遇到错误。首先,我必须确定它是JSONObject还是JSONArray

JSON 数组由 [] 覆盖,对象由 {} 覆盖

所以,我添加了这段代码

if (response.startsWith("[")) {
  //JSON Array
} else {
  //JSON Object 
}
Run Code Online (Sandbox Code Playgroud)

这对我有用,我希望它对你也有帮助,因为这只是一个简单的方法

在此处查看有关 String.startsWith 的更多信息 - https://www.w3schools.com/java/ref_string_startswith.asp