Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Parsing and Nullable int value in android

Tags:

java

json

android

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

Case 1 :

     {

                 OWNER_ID : 145
     }

Case 2 :

     {

                  OWNER_ID : null
     }

Now in order to parse the data I am using the following statement :

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

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

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

But still I am not able to parse the data successfully. Can any one help me? How to parse the int value in general so that it won't show any Exception?

Thank you in advance.

like image 608
user3080161 Avatar asked Dec 02 '22 18:12

user3080161


1 Answers

Try this way, hope this will help you to solve your problem.

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

jsonObject.optInt("OWNER_ID");

Or

jsonObject.optInt("OWNER_ID", 0);
like image 56
Haresh Chhelana Avatar answered Dec 05 '22 08:12

Haresh Chhelana