当json包含没有键的数组时,如何检查swiftyJSON中是否存在键

时间:2016-05-11 15:50:28

标签: ios json swift swifty-json

我知道swiftyJSON方法exists()但它似乎并不像他们所说的那样工作。 在下面这种情况下如何获得正确的结果?我无法更改JSON结构,因为我通过客户端API获取此信息。

var json: JSON =  ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
    print("response someKey exists")
}

输出:

response someKey exists

不应该打印,因为someKey不存在。但有时候这个密钥来自客户端的API,我需要找出它是否存在。

1 个答案:

答案 0 :(得分:22)

它不适用于你的情况,因为json["response"]的内容不是字典,它是一个数组。 SwiftyJSON无法检查数组中的有效字典键。

使用字典,它可以工作,条件不会按预期执行:

var json: JSON =  ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
    print("response someKey exists")
}

您的问题的解决方案是在使用.exists()之前检查内容是否确实是字典:

if let _ = json["response"].dictionary {
    if json["response"]["someKey"].exists() {
        print("response someKey exists")
    }
}