Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if parsed json is NSNULL

Tags:

json

swift

nsnull

I am parsing a JSON response and trying to check if one of my keys is null. How would I go about this? I have the following:

var routingNumber = (dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber") as! String

and this returns:

Could not cast value of type 'NSNull' (0x107d238c8) to 'NSString' (0x107329c40).

How would I check if the value is NSNULL?

if( something != NSNULL){
    do something
}else{
    do something else
}
like image 870
user2423476 Avatar asked Feb 23 '17 05:02

user2423476


2 Answers

You can extract value from dic like this.

if let value = (dict["key"] as? String) 
{ 
  //NOT NULL
} 
else 
{
   //NULL
}
like image 78
Amit Singh Avatar answered Oct 15 '22 14:10

Amit Singh


create below function

func isNsnullOrNil(object : AnyObject?) -> Bool
{
    if (object is NSNull) || (object == nil)
    {
        return true
    }
    else
    {
        return false
    }
}

call function where you want to check for null or nil value

if isNsnullOrNil((dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber"))
{
    print("object is null or nil")
}
else
{
    print("object is not  null or nil")
}
like image 34
Chetan Hedamba Avatar answered Oct 15 '22 14:10

Chetan Hedamba