JSON Parser check integer is Null in Java Android


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

   duration: null

Right in the sentence:


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

2 answers


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


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

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


or we can specify an integer for null :



answered by 21.01.2016 в 15:53