Json Parsing and Nullable int value in android

I have a json object as I showed in two cases: -

Case 1:

     {

                 OWNER_ID : 145
     }

      

Case 2:

     {

                  OWNER_ID : null
     }

      

Now, to parse the data, I use the following statement:

int note_owner_id = jsonObject.getInt("OWNER_ID");

      

I am aware of that in java we need to use a wrapper class to extract a NULL integer and the code should be written like this: -

Integer note_owner_id = jsonObject.getInt("OWNER_ID");

      

But still I cannot successfully parse the data. Can anyone help me? How to parse an int value at all so that it doesn't show an Exception?

Thanks in advance.

+4


source to share


5 answers


Try this way, hope it helps you solve your problem.

Instead of getInt (string name) try using optInt (String name) or optInt (string name, int fallBack) , which will handle a null value:

jsonObject.optInt("OWNER_ID");

      



Or

jsonObject.optInt("OWNER_ID", 0);

      

+9


source


You can install Integer

with ternary andisNull(String)



Integer note_owner_id = (jsonObject.isNull("OWNER_ID")) ? null :
     jsonObject.getInt("OWNER_ID");

      

+2


source


you can use optInt

public int optInt (row name)

Returns the value displayed by name if it exists and is an int, or can be coerced into an int, or 0 otherwise.

to handle null values ​​like

jsonObject.optInt("OWNER_ID");

      

or

jsonObject.optInt("OWNER_ID", defaultValue);

      

+2


source


just add below line to check if your variable is null or not: -

if(jsonObject.isNULL("OWNER_ID"))
{
    // code here when data is null
}
else
{
    int note_owner_id = jsonObject.getInt("OWNER_ID");
}

      

0


source


You can use "Opt" for Json when it is Nullable and it's easy. Instead of getInt or getString, use:

int anything= json.optInt( "any", 0 );

      

0


source







All Articles