Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if getJSONArray is null or not

Tags:

java

json

android

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(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 ?

like image 404
toshiro92 Avatar asked Aug 18 '11 15:08

toshiro92


People also ask

How do I check if a JsonObject is null?

Return valueJsonObject::isNull() returns a bool that tells if the JsonObject points to something: true if the JsonObject is null, false if the JsonObject is valid and points to an object.

How do I check if a JsonArray is null?

Return valueJsonArray::isNull() returns a bool that tells if the JsonArray points to something: true if the JsonArray is null, false if the JsonArray is valid and points to an array.

How check JsonObject is null or not in android?

Try with json. isNull( "field-name" ) .

Can a JSON object be null?

Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.


2 Answers

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);
        }
   }
like image 54
Kevin Avatar answered Oct 05 '22 13:10

Kevin


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?

like image 20
njzk2 Avatar answered Oct 05 '22 13:10

njzk2