繁体   English   中英

检查JSON对象是否为null swift 3

[英]Check if JSON object null swift 3

我很难检查此JSON对象是否为null。 带和不带客户密钥的示例JSON。

这就是finalValue等于=

使用客户密钥:

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

没有客户密钥:

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

这是我尝试检查的方法,但始终转到else语句。

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

您可以只使用可选的链接

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

斯威夫特3.0

使用SwiftyJSON,有一个函数exist 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")
        }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM