Test if getJSONArray is null or not
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :
org.json.JSONException: No value for 1
My code :
JSONObject obj = new JSONObject(resul开发者_如何学Ct);
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 ?
use obj.optJSONArray(name)
the response will be null if the name does not exists.
JSONObject obj = new JSONObject(result);
for(int i=1;i<=14;i++) {
JSONArray arr = obj.optJSONArray(""+i);
if(arr != null) {
extraction(arr, i);
}
}
use JSONObject.optJSONArray(key).
As indicated in the documentation, it returns null in case the key is not present.
Also, your JSON structure seems weird. Why do you have numeric ordered keys in an object? shouldn't that be an Array?
You cannot use .length() for check the return null of JSONArray. Use .isNull("xxx") instead of .length(), the example is below:
JSONArray magazineLove = null;
if(!socialBook.getJSONObject(i).isNull("MagazineLove"))
{
magazineLove = socialBook.getJSONObject(i).getJSONArray("MagazineLove");
}
Aey.Sakon
精彩评论