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 to share
You can install Integer
with ternary andisNull(String)
Integer note_owner_id = (jsonObject.isNull("OWNER_ID")) ? null :
jsonObject.getInt("OWNER_ID");
+2
source to share