迅速.如何处理json文件中的空值?

Fra*_*ega 13 null json ios swift

我正在从URL读取json,并且(我在ObjectiveC中遇到了同样的问题)这些值会导致我的应用程序崩溃.我对字符串和数字没有任何问题.我可以println(值)但是当我将值分配给UILabel时,它会崩溃.

我用这个方法来读取JSON:

func jsonFromURL(jsonURL: String) -> Dictionary<String, AnyObject> {
    var jsonNSURL: NSURL = NSURL(string: jsonURL)
    let jsonSource: NSData = NSData(contentsOfURL: jsonNSURL)
    var json = NSJSONSerialization.JSONObjectWithData(jsonSource, options:NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
    return json
}
Run Code Online (Sandbox Code Playgroud)

...以及此代码将值分配给自定义Cell中的UILabel

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {

    var regularTextCell:celda = celda(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    var cell:celda = NSBundle.mainBundle().loadNibNamed("celda", owner: self, options: nil)[0] as celda

    cell.name.text = myJson["list"]![indexPath.row]!["name"] as String
    cell.id.text = "id: " + String(myJson["list"]![indexPath.row]!["id"] as Int)

    // THIS line crash because some values of adress are <null>
    cell.address.text = myJson["list"]![indexPath.row]!["address"] as String

    return cell

}
Run Code Online (Sandbox Code Playgroud)

您可以在以下位置查看JSON的示例:https://dl.dropboxusercontent.com/u/787784/example.json

谢谢!

GoZ*_*ner 17

您将从语法中获得异常,object as String如果object不是a String.您可以通过使用object as? String可能导致nil分配到您的例外来避免异常text.

在您的具体情况下,您可以使用:

cell.address.text = (myJson["list"]![indexPath.row]!["address"] as? String) ?? "default"
Run Code Online (Sandbox Code Playgroud)

我替换你as的地方as?并利用了nil-coalescing运算符??.


小智 9

我在在线Swift教程中找到了这个解决方案.如何在Swift中处理null值是非常好的解决方案.

这是概念:

 let finalVariable = possiblyNilVariable ?? "Definitely Not Nil Variable"
Run Code Online (Sandbox Code Playgroud)

在教程示例中:

  let thumbnailURL = result["artworkUrl60"] as? String ?? ""
Run Code Online (Sandbox Code Playgroud)

这是教程的链接:http: //jamesonquave.com/blog/developing-ios-8-apps-using-swift-interaction-with-multiple-views/


Jia*_*aro 6

您可以将违规行更改为:

if let address = myJson["list"]![indexPath.row]!["address"] as? String {
  cell.address.text = address
}
else {
  cell.address.text = ""
}
Run Code Online (Sandbox Code Playgroud)

as?运营商将投值以同样的方式as想,但如果铸造失败,它将代替分配nil

if let …语法与检查相结合这一点,当铸造失败(并返回nil)else块,而不是运行