Search code examples
iosswiftswift3native

Check if JSON object null swift 3


I'm having a hard time checking if this JSON object is null. Example JSONs with and without customer key.

This is what finalValue equals =

With customer key:

{
  "customer" : { 
      "href" : "myURL"
  },
  "token": "781hjasf98123bjwef8"
}

without customer key:

{ 
    "error" : {
        "message" : "Unauthorized"
    }
}

This is how I try to check, but it always goes to else statement.

            if let value = response.result.value{
                let finalValue = JSON(value)
                if finalValue["customer"] is NSNull{
                    print("if part")
                }else{
                    print("Else part")
                }
            }

Solution

  • Swift 3.0

    Using SwiftyJSON, there is function exists() for checking key is exist or not.

    if let value = response.result.value {
            let finalValue = JSON(value)
            if finalValue["customer"].exists() {
                print("if value exists then this part will be executed")
            } else {
                print("if value no longer then this part will be executed")
            }
     }
    

    Without SwiftyJSON

    if let value = response.result.value {
            if dictionary.index(forKey: "customer") != nil {
                print("if value exists then this part will be executed")
            } else {
                print("if value no longer then this part will be executed")
            }
     }