If getJSONArray is null or not

My code retrieves the JSONObject results, but sometimes the value I do not start with 1, and I have this error:

org.json.JSONException: No value for 1 

My code is:

 JSONObject obj = new JSONObject(result); for(int i=1;i<=14;i++) { JSONArray arr = obj.getJSONArray(""+i); extraction(arr, i); } 

I want to check before retrieving if the object code (i) exists or not. How can i do this?

+6
source share
3 answers

use obj.optJSONArray(name) answer will be empty if the name does not exist.

 JSONObject obj = new JSONObject(result); for(int i=1;i<=14;i++) { JSONArray arr = obj.optJSONArray(""+i); if(arr != null) { extraction(arr, i); } } 
+12
source

use JSONObject.optJSONArray(key).

As stated in the documentation, it returns null if the key is missing.

Also, your JSON structure seems weird. Why do you have numeric ordered keys in an object? Shouldn't be an Array?

+3
source

You cannot use .length () to check for a zero JSONArray return value. Use .isNull ("xxx") instead of .length (), an example below:

 JSONArray magazineLove = null; if(!socialBook.getJSONObject(i).isNull("MagazineLove")) { magazineLove = socialBook.getJSONObject(i).getJSONArray("MagazineLove"); } 

Aey.Sakon

0
source

Source: https://habr.com/ru/post/895340/


All Articles