【问题标题】:swiftyJSON check if value is nullswiftyJSON 检查值是否为空
【发布时间】:2018-08-12 22:38:45
【问题描述】:

我有一个 json,它是字典数组

response.text = [{
"id": "4635465675",
"name": "Arts",
"pluralName": "Arts",
"shortName": null
}]

json = JSON((response.text)?.data(using: .utf8)) 我如何检查键“shortName”的值是否为空,例如数组中的第一个字典? 我试着这样做

if json[0]["shortName"] is NSNull

但它总是正确的。 我该如何处理?

【问题讨论】:

  • 试试这个if json["shortName"] is nil。或if let shortName = json["shortName"] { print("shortName - \(shortName)") } else { print("shortName is nil") }
  • 如果让 _ = json["shortName"] 为? String { // 不为空 }
  • json[0]["shortName"] is NSNull 但这总是正确的。我该如何处理它? 当然它会是真的,因为它是空的
  • 但是您的 json 是字典,说 [String:String],而不是字典对象数组 [[String:String]],所以我不知道您为什么要尝试使用访问 json 的第一个元素索引[0]
  • @Krunal 完整的 json [{ "id": "4635465675", "name": "Arts", "pluralName": "Arts", "shortName": null }] 和 json 变量 var json = JSON((response.text)?.data(using: .utf8))

标签: ios swift swifty-json


【解决方案1】:

执行下面的代码看看

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"])")
    }


}

在此处分享此代码的结果。

【讨论】:

  • 错误:条件绑定的初始化程序必须具有可选类型
  • 所有行返回“不存在或为空/无”
  • 这一行的准确输出 - print("shortName does not exist or it is null/nil - \(jsonObject["shortName"])") ?
【解决方案2】:

好吧,这比我想象的要容易

if json[0]["shortName"].string == nil {
//null
}else{
//not null
}

【讨论】:

    【解决方案3】:

    你可以直接检查为JSON.null的key

    if json[0]["shortName"] == JSON.null {
    // show the alert
    
    }
    

    如果它是你的字符串

    if json[0]["shortName"].string == nil {
    

    【讨论】:

    • 是的,这正是我所需要的。谢谢
    • 不应该将if json[0]["shortName"].stringValue == nil{ 更改为if json[0]["shortName"].stringValue == ""{,因为stringValue 总是返回String 而不是String?
    • @WimukthiRajapaksha- 感谢您的评论,我们也可以使用 if let getShortName = json[0]["shortName"].string,!getShortName.isEmpty { print(getShortName) }
    猜你喜欢
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2013-05-11
    • 1970-01-01
    • 2022-12-31
    • 2015-02-08
    相关资源
    最近更新 更多