【问题标题】:How To Handle json null values in Swift如何在 Swift 中处理 json null 值
【发布时间】:2016-06-03 05:12:31
【问题描述】:

过去两天我一直在玩 JSON,遇到了很多奇怪的问题,感谢堆栈溢出,这对我有帮助。这是 JSON 特色键有两种类型的字符串值。

 "featured":"1"

"featured": null,

我尝试了很多来解决这个问题,但失败了

第 1 步:

 if dict.objectForKey("featured") as? String != nil {
    featured = dict.objectForKey("featured") as? String
    }

第 2 步:

    let null = NSNull()
    if dict.objectForKey("featured") as? String != null {
    featured = dict.objectForKey("featured") as? String
    }

第 3 步:

    if dict.objectForKey("featured") as? String != "" {
    featured = dict.objectForKey("featured") as? String
    }

但不幸的是找不到解决方案,您的回答将不胜感激。

【问题讨论】:

  • 它会导致崩溃吗?
  • 是的,在存储核心数据时

标签: json swift core-data null


【解决方案1】:

试试这个

func nullToNil(value : AnyObject?) -> AnyObject? {
    if value is NSNull {
        return nil
    } else {
        return value
    }
}

object.feature = nullToNil(dict["feature"])

在这里,您可以使用此方法,它将 null 值转换为 nil,并且不会导致您的应用程序崩溃。

您也可以使用 as?

object.feature = dict["feature"] as? NSNumber

谢谢。

【讨论】:

  • 10000000 up 投票支持这个答案。
  • 这太棒了,谢谢!如果您使用的是 Alamofire 和 SwiftyJSON,则必须强制向下转换为 AnyObject 才能使其工作。 =D 我的示例如下所示: object["feature"] : JSON 我的 null 检查如下所示: if nullToNil(value: object["feature"] as AnyObject) != nill { // 做某事 }
【解决方案2】:

这是一个有效的代码,类型转换操作符(as?)将在这里解决问题。 Null 不会被类型转换为 String,因此执行将进入失败块。

if let featured = dict["featured"] as? String {
    print("Success")
}
else {
    print("Failure")
}

【讨论】:

    【解决方案3】:

    试试这个!

    if let demoQuestion = dict.objectForKey("featured"){
         let getValue: String = demoQuestion as! String
    }
    else {
    print("JSON is returning nil")
    }
    

    【讨论】:

      【解决方案4】:

      if let 或其对应物guard let 的可选链接是可行的方法。所有三个步骤相结合(缺失、错误类型 - NSNull 也是、空字符串):

      guard let featured = dict.objectForKey("featured") as? String where !value.isEmpty else {
          print("featured has wrong value")
      }
      
      // do what you need to do with featured
      

      如果您想了解更多关于可选链的信息check out documentation

      【讨论】:

        【解决方案5】:

        您好,您可以使用以下函数将 null 删除为空字符串并防止崩溃

        func removeNullFromDict (dict : NSMutableDictionary) -> NSMutableDictionary
        {
            let dic = dict;
        
            for (key, value) in dict {
        
                let val : NSObject = value as! NSObject;
                if(val.isEqual(NSNull()))
                {
                    dic.setValue("", forKey: (key as? String)!)
                }
                else
                {
                    dic.setValue(value, forKey: key as! String)
                }
        
            }
        
            return dic;
        }
        

        在以以下方式将dict赋予任何方法调用函数之前

        let newdict = self.removeNullFromDict(dict: dict);
        

        【讨论】:

          【解决方案6】:

          我做了一个静态函数来将值从 json 转换为可选字符串。

          class Tools{
          
              static func setOptionalStr(value : Any?) -> String?{
                  guard let string = value as! String?, !string.isEmpty else {
                      return nil
                  }
                  return  value as? String
              }
          }
          

          在我的控制器中

          let urlStats: String? = Tools.setOptionalStr(value: json["UrlStats"])
          

          我愿意接受您的反馈

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-09-25
            • 1970-01-01
            • 2015-03-18
            • 1970-01-01
            • 1970-01-01
            • 2010-12-25
            • 1970-01-01
            • 2017-04-29
            相关资源
            最近更新 更多