Reputation: 2244
I'm trying to get values from Json object and I have a problem. I'm using getint function to get value but the value is null and getint function gving error.
How can I solve this problem?
Code :
firmInfo.setFirmID(object.getInt(Constants.FirmID));
Thanks.
Upvotes: 16
Views: 12184
Reputation: 2033
getint
gives error message if there is no such key in JSONObject or your error is while setting it to firmInfo
check whether the id is present or not using
object.has("Constants.FirmID")
if it has the key , check whether it is null or not
if(String.valueOf(jArray.getInt("sdfgh")) != null)
{
// add your code here . . . . .
}
or
if(String.valueOf(jArray.getInt("sdfgh")).length < 1)
{
// add your code here . . . . .
}
Upvotes: -2
Reputation: 12239
You can check if the object you recieve is an instanceof JSONObject
before you try to getInt()
. Also you need to check if null before passing as a param
to your getInt()
. Like below
if(Constants.FirmID != null){
firmInfo.setFirmID(object.getInt(Integer.parseInt(Constants.FirmID)));
}
Check this link
Upvotes: -1
Reputation: 43728
Assuming that object
is of type JSONObject
you can use
object.optInt(Constants.FirmID)
or
object.optInt(Constants.FirmID, defaultValue)
Upvotes: 45