检查 JSON 对象是否为 null swift 3
Check if JSON object null swift 3
我很难检查此 JSON 对象是否为空。示例 JSONs 有和没有客户密钥。
这就是 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")
}
}
Swift 3.0
使用SwiftyJSON,有功能exists()
检查key是否存在。
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")
}
}
您可以只使用可选链接:
if let finalValue = finalValue["customer"] as? String {
// there's a value!
}
我很难检查此 JSON 对象是否为空。示例 JSONs 有和没有客户密钥。
这就是 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")
}
}
Swift 3.0
使用SwiftyJSON,有功能exists()
检查key是否存在。
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")
}
}
您可以只使用可选链接:
if let finalValue = finalValue["customer"] as? String {
// there's a value!
}