主要介绍了swiftyJSON检查value是否为null相关的知识,希望对你有一定的参考价值。
我有一个json是字典数组
response.text = [
"id": "4635465675",
"name": "Arts",
"pluralName": "Arts",
"shortName": null
]
json = JSON((response.text)?.data(using: .utf8))我如何检查键“shortName”的值是否为null,比如数组中的第一个字典?我试着这样做
if json[0]["shortName"] is NSNull
但它总是如此。我怎么处理它?
答案
你可以直接检查JSON.null的关键
if json[0]["shortName"] == JSON.null
// show the alert
如果它是你的字符串
if json[0]["shortName"].stringValue == nil
另一答案
执行以下代码并查看
let jsonArray = [ "id": "4635465675", "name": "Arts", "pluralName": "Arts", "shortName": null ]
if let jsonObject = jsonArray[0] as? [String : Any]
if let id = jsonObject["id"] as? String
print("id - \(id)")
else
print("id does not exist or it is null/nil")
if let name = jsonObject["name"] as? String
print("name - \(name)")
else
print("name does not exist or it is null/nil")
if let pluralName = jsonObject["pluralName"] as? String
print("pluralName - \(pluralName)")
else
print("pluralName does not exist or it is null/nil")
if let shortName = jsonObject["shortName"] as? String
print("shortName - \(shortName)")
else
print("shortName does not exist or it is null/nil - \(jsonObject["shortName"])")
在这里分享此代码的结果。
另一答案
好吧,那比我想的要容易
if json[0]["shortName"].string == nil
//null
else
//not null
更多知识 请参考
https://it.cha138.com/tech/show-1798393.html