ios - swift 。如何将空值处理为 json 文件?

标签 ios json null swift

我正在从 URL 读取 json,并且再次(我与 ObjectiveC 有同样的问题)这些值使我的应用程序崩溃。我对字符串和数字没有任何问题。我可以 println(value) 但当我将值分配给 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
}

...以及将值分配到自定义单元格内的 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

}

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

谢谢!

最佳答案

如果 object 不是 String,您会从类似 object as String 的语法中得到一个异常。您可以通过使用 object as? String 可能会导致 nil 被分配到您的 text 中。

在您的特定情况下,您可以使用:

cell.address.text = (myJson["list"]![indexPath.row]!["address"] as? String) ?? "default"

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

关于ios - swift 。如何将空值处理为 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24128531/

相关文章:

json - JSON 字符串中出现意外的 nil

c# - 即使表中的列不允许为空,空文本框仍将数据保存在 SQL Server 中

ios - 在 Swift 中使用协议(protocol)和委托(delegate)在两个类之间进行通信 - 不起作用,请参阅代码

ios - 如何计算不同方向的 iOS 11 尺寸?

ios - 从 NSDate 获取每分钟的小时数

javascript - 对象不支持属性或方法 jquery 插件

java - 从返回 null 的源文件夹加载图像

ios - SpriteKit 粒子发射器未出现在 Xcode 编辑器中

javascript - 如何使用 jQuery 的 json2html 将文件内的文本渲染到另一个 html 页面中?

php - 从 PHP INNER JOIN 表创建多维 JSON