I know about swiftyJSON method exists() but it does not seem to work always as they say. How can I get proper result in this case below? I cannot change JSON structure because I am getting this through client's API.
我知道swift json方法的存在(),但它似乎并不总是像人们说的那样工作。在下面这个例子中,我如何得到正确的结果?我不能改变JSON结构,因为我是通过客户端API实现的。
var json: JSON = ["response": ["value1","value2"]]
if json["response"]["someKey"].exists(){
print("response someKey exists")
}
Output:
输出:
response someKey exists
That shouldn't be printed because someKey does not exist. But sometimes that key comes from client's API, and i need to find out if it exists or not properly.
不应该打印,因为有些键不存在。但是有时候这个密钥来自客户端的API,我需要知道它是否存在。
1 个解决方案
#1
14
It doesn't work in your case because the content of json["response"]
is not a dictionary, it's an array. SwiftyJSON can't check for a valid dictionary key in an array.
它在您的例子中不起作用,因为json["response"]的内容不是字典,而是数组。SwiftyJSON不能检查数组中的有效字典键。
With a dictionary, it works, the condition is not executed, as expected:
有了字典,它就工作了,条件没有执行,如预期的那样:
var json: JSON = ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
The solution to your issue is to check if the content is indeed a dictionary before using .exists()
:
解决您的问题的方法是在使用.exist()之前检查内容是否确实是字典:
if let _ = json["response"].dictionary {
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
}
#1
14
It doesn't work in your case because the content of json["response"]
is not a dictionary, it's an array. SwiftyJSON can't check for a valid dictionary key in an array.
它在您的例子中不起作用,因为json["response"]的内容不是字典,而是数组。SwiftyJSON不能检查数组中的有效字典键。
With a dictionary, it works, the condition is not executed, as expected:
有了字典,它就工作了,条件没有执行,如预期的那样:
var json: JSON = ["response": ["key1":"value1", "key2":"value2"]]
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
The solution to your issue is to check if the content is indeed a dictionary before using .exists()
:
解决您的问题的方法是在使用.exist()之前检查内容是否确实是字典:
if let _ = json["response"].dictionary {
if json["response"]["someKey"].exists() {
print("response someKey exists")
}
}