java 测试 getJSONArray 是否为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7110066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if getJSONArray is null or not
提问by toshiro92
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :
我的代码提取了 JSONObject 的结果,但是,有时 i 值不会从 1 开始,并且我有这样的错误:
org.json.JSONException: No value for 1
My code :
我的代码:
JSONObject obj = new JSONObject(result);
for(int i=1;i<=14;i++) {
JSONArray arr = obj.getJSONArray(""+i);
extraction(arr, i);
}
I want to test before the extraction if the object code (i) exists or not. How i can do this ?
我想在提取之前测试目标代码(i)是否存在。我怎么能做到这一点?
回答by Kevin
use obj.optJSONArray(name)
the response will be null if the name does not exists.
obj.optJSONArray(name)
如果名称不存在,则使用响应将为空。
JSONObject obj = new JSONObject(result);
for(int i=1;i<=14;i++) {
JSONArray arr = obj.optJSONArray(""+i);
if(arr != null) {
extraction(arr, i);
}
}
回答by njzk2
use JSONObject.optJSONArray(key).
利用 JSONObject.optJSONArray(key).
As indicated in the documentation, it returns null in case the key is not present.
如文档中所示,如果密钥不存在,它将返回 null。
Also, your JSON structure seems weird. Why do you have numeric ordered keys in an object? shouldn't that be an Array?
此外,您的 JSON 结构似乎很奇怪。为什么对象中有数字有序键?那不应该是一个数组吗?
回答by user3113670
You cannot use .length() for check the return null of JSONArray. Use .isNull("xxx") instead of .length(), the example is below:
您不能使用 .length() 来检查 JSONArray 的返回空值。使用 .isNull("xxx") 而不是 .length(),示例如下:
JSONArray magazineLove = null;
if(!socialBook.getJSONObject(i).isNull("MagazineLove"))
{
magazineLove = socialBook.getJSONObject(i).getJSONArray("MagazineLove");
}
Aey.Sakon
爱沙空