简体   繁体   English

迅速。 如何处理null值到json文件中?

[英]Swift. How can I deal with null values into json files?

I'm reading json from a URL and, again (I had the same issue with ObjectiveC) the values crash my app. 我正在从URL中读取json,然后(我在ObjectiveC中遇到了同样的问题)这些值使我的应用崩溃了。 I don't have any problems with Strings and Numbers. 我对字符串和数字没有任何问题。 I can println(value) but when I assign the value into a UILabel, it crashes. 我可以使用println(value),但是将值分配给UILabel时会崩溃。

I use this method to read the JSON: 我使用这种方法来读取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
}

...and this code to assign values into a UILabel inside a custom 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

}

You can view an example of the JSON at: https://dl.dropboxusercontent.com/u/787784/example.json 您可以在以下位置查看JSON的示例: https : //dl.dropboxusercontent.com/u/787784/example.json

Thanks! 谢谢!

You'll get an exception from syntax like object as String if object is not a String . 你会得到类似的语法异常object as String ,如果object是不是String You can avoid the exception by using object as? String 您可以通过使用object as? String来避免异常object as? String object as? String which may result in a nil being assigned into your text . object as? String ,可能会导致nil被分配给您的text

In your specific case you could use: 在您的特定情况下,您可以使用:

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

where I've replaced your as with as? 在那里我已经更换了你asas? and exploited the nil-coalescing operator ?? 并利用了零促销运营商?? .

I found this solution in online Swift tutorial. 我在在线Swift教程中找到了该解决方案。 It's very nice solution how to deal with null value in Swift. 如何在Swift中处理null值是一个非常好的解决方案。

This is the concept: 这是概念:

 let finalVariable = possiblyNilVariable ?? "Definitely Not Nil Variable"

In tutorial example : 在教程示例中:

  let thumbnailURL = result["artworkUrl60"] as? String ?? ""

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

You can change the offending line to: 您可以将违规行更改为:

if let address = myJson["list"]![indexPath.row]!["address"] as? String {
  cell.address.text = address
}
else {
  cell.address.text = ""
}

The as? as? operator will cast the value the same way as would, but if the casting fails, it will instead assign nil 运营商将投价值的方式相同as会,但如果铸造失败,它将代替分配nil

The if let … syntax combines this with a check and when the casting fails (and nil is returned) the else block runs instead if let …语法将此内容与检查结合在一起,当强制转换失败(并返回nil)时,则运行else块

If you use: 如果您使用:

You'll be able to go like this: 您将可以像这样去:

let yourJSON = JSON.fromURL("https://dl.dropboxusercontent.com/u/787784/example.json")
for (i, node) in yourJSON["list"] {
    let isnull = node["address"].isNull
    println("//[\"list\"][\(i)]:\t\(isnull)")
}

//["list"][0]:  false
//["list"][1]:  false
//["list"][2]:  true
//["list"][3]:  false
//["list"][4]:  false
//["list"][5]:  true
//["list"][6]:  false
//["list"][7]:  false
//["list"][8]:  false
//["list"][9]:  false
//["list"][10]: false
//["list"][11]: false
//["list"][12]: true
//["list"][13]: false
//["list"][14]: false
//["list"][15]: false
//["list"][16]: false
//["list"][17]: false
//["list"][18]: false
//["list"][19]: false

No ? 不是? or ! ! required and it does not crash on nonexistent nodes. 必需,并且不会在不存在的节点上崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 swift。 如何将计算结果传递到另一个屏幕? - swift. How can I pass the calculation result to another screen? prepareForSegue不能快速运行。 我该如何解决? - prepareForSegue doesn't work in swift. How can i resolve it? 如何在 swift 中创建 iCal 事件并下载/导出事件 in.ics 文件。 我想要在我的 iPhone 文件中的文件 - How can I create iCal events and download/export event in .ics file in swift. I want file in Files in my iPhone 如何在 Swift 中使用 Decodable 解析 JSON 元素。 这样做时我收到错误 - How to parse JSON Element with Decodable in Swift. I receive errors when doing so 我在Swift中创建了一个UIImage作为视频的快照。 我如何获得它的临时路径? - I created a UIImage as a snapshot of my video in Swift. How can I get a temporary path to it? 在iOS Swift中进行本地化。 我如何在运行时更改应用程序语言 - localization in ios swift. how can i change application language at run time navigationController?.isNavigationBarHidden = true导致Swift中出现NSRangeException。 我该如何预防? - navigationController?.isNavigationBarHidden = true causes NSRangeException in Swift. How can I prevent it? 在ObjC中工作,而不是很快。 我在快速处理JSON解析时出了什么问题 - Working in ObjC, not in swift. Whats wrong I am doing with JSON parsing in swift 如何使用触摸开始从按钮获取值快速开始功能。? - how to get values from button using touches began function in swift.? 我想快速制作一个翻译应用程序。 谁能帮我? - I want to make a translation app in swift. Can anyone help me?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM