检查JSON对象是否为null swift 3

时间:2017-08-30 10:50:17

标签: ios swift swift3 native

我很难检查这个JSON对象是否为空。带或不带客户密钥的示例JSON。

这就是finalValue等于=

使用客户密钥:

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

没有客户密钥:

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

这是我尝试检查的方式,但它始终用于其他声明。

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

2 个答案:

答案 0 :(得分:2)

您可以使用可选链接

if let finalValue = finalValue["customer"] as? String {
    // there's a value!
}

答案 1 :(得分:0)

Swift 3.0

使用SwiftyJSON,有一个函数exists()用于检查密钥是否存在。

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")
        }
 }

没有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")
        }
 }