JSON Parser check integer is Null in Java Android

4

I get a JSON that sometimes the numeric fields have value or null :

{
   duration: null
}

Right in the sentence:

jArray.getJSONObject(id).getInt("duration");

The error occurs:

W/System.err: org.json.JSONException: Value null at duration of type org.json.JSONObject$1 cannot be converted to int
    
asked by Webserveis 21.01.2016 в 15:53
source

2 answers

4

Before trying to get the value, you can use isNull to verify if the value is null or does not exist.

Example:

JSONObject obj = jArray.getJSONObject(id);
if (!obj.isNull("duration")) { 
    valor = obj.getInt("duration");
}

If you need to know if the value is indeed null (it exists but it is null), it is a bit more complicated.

if(obj.has("duration") && obj.isNull("duration")) { 
   // el valor existe, pero es null. 
}

As usual, null I could have a meaning tristate , you will have to consider each case before making your decision.

In addition, the previous answer already says, it is also optInt (and optString, optLong, etc), but this method will give you the default value, even if the field was not set at all. So you should opt for one or another option according to the needs of the case.

    
answered by 21.01.2016 / 16:53
source
2

To parse nulls to integer you must replace getInt with optInt :

.optInt("json_field");

or we can specify an integer for null :

.optInt("json_field",0);

Example:

jArray.getJSONObject(id).optInt("duration",0);
    
answered by 21.01.2016 в 15:53