我正在从网站获取 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 对象和数组分别是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
}
关于java - 如何检查给定对象是JSON字符串中的对象还是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9817315/