swiftyJSON检查value是否为null

主要介绍了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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值