【问题标题】:swift how can I check for NULL values coming from Jsonswift 如何检查来自 Json 的 NULL 值
【发布时间】:2017-04-15 04:14:49
【问题描述】:

我有一个 rest api,我通过 Json 获取所有数据,然后将其放入 IOS TableView。我的问题是某些数据在 Json 中以 NULL 的形式返回

"vote_status":null

我正在尝试快速获取 NULL 值并将其更改为字符串“0”,但我很难这样做。到目前为止我有这个

  if var vote_status = Stream["vote_status"] as? String {
                                if (vote_status == (vote_status)[NSNull]) {
                                   vote_status = "0"
                                }
}

但是我得到这个编译错误:

不能用类型索引为“String”类型的值下标 '(NSNull).Type'(又名'NSNull.Type')

我这样做是因为 nilnull 似乎不起作用,所以我不能这样做。

if (vote_status == nil) ...

【问题讨论】:

  • 如果您将从 JSON 获取的字典打印到控制台,您会看到什么?
  • 如果我打印它;它根本不返回任何东西,甚至不返回 NULL 它只是空白
  • 除非我们知道您如何将 JSON 字符串转换为对象,否则无法回答这个问题。

标签: json swift swift3 nsnull


【解决方案1】:

您只需有条件地将字典值转换为 String 并使用 Nil Coalescing Operator ?? 分配 "0" 以防失败 null

let vote_status = Stream["vote_status"] as? String ?? "0"

【讨论】:

    【解决方案2】:

    Swift 3.0

    func checkNull(obj : AnyObject?) -> AnyObject? {
        if obj is NSNull {
            return nil
        } else {
            return value
        }
    }
    
    object.feature = checkNull(dict["feature"])
    

    试试这个

    vote_status is NSNull 
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

      func checkForNull(value:AnyObject) -> String
          {
              if(value as! NSObject == NSNull() || value as! String == "")
              {
                 return " "
              }
              else
              {
                  return value as! String
              }
          }
      

      【讨论】:

        【解决方案4】:

        试试这样的:

        if let category = Stream["vote_status"] as? String {
                                print(category)
                            } else {
                                print(category)
                            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-26
          • 2015-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多