我正在从 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/