【问题标题】:How do I parse and store an integer value from a json dictionary in swift?如何快速解析和存储 json 字典中的整数值?
【发布时间】:2014-10-02 16:46:45
【问题描述】:

我已经解析了一个 JSON 数组并提取了一个 NSDictionary 并从中提取了一个 String 变量并通过 segue 成功地将它传递给我的下一个视图。当我尝试对整数执行相同操作时,应用程序崩溃...

这是我的代码:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "genreSegue" {
        println("genreSegue")
        let indexPath = self.tableView.indexPathForSelectedRow()
        println("row: \(indexPath.row)")
        var bookView:BookViewController = segue.destinationViewController as BookViewController

        if let genres = self.genreList as? [NSDictionary] {
            var item = genres[indexPath.row]
            println("segueItem: \(item)")
            let title:String = item["title"] as String
            let genreId:Int = item["id"] as Int  // this line crashes the app
            let genreId:NSNumber = item["id"] as NSNumber // this version also crashes
            println("title: \(title)")
            bookView.genreTitle = item["title"] as String
            //bookView.genreId = item["id"] as Int  // so I can't test this line
        }
    }
}

这是控制台输出:

genreSegue
row: 1
segueItem: {
    id = 2;
    records = 1;
    selfLink = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/id/2";
    title = Biography;
}
title: Biography

这是线程 1 上的错误: libswift_stdlib_core.dylib`swift_dynamicCastObjCClassUnconditional:

这里是原始的json数据:

http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list

这是我的应用程序源代码:

https://github.com/marktyers/ios_bookshop_client

我看不到字符串变量是如何工作的,但不是 int。有什么想法吗?

【问题讨论】:

  • 或许,崩溃报告和实际的 JSON 会提供更多信息。 ;)
  • 盲射远:NSJSONSerialization 给你一个NSNumber 对象。也许您正在尝试将其分配给原始 Int
  • 很好,但是修改了我的代码,如果我使用 NSNumber,我会遇到同样的崩溃......
  • 如果您尝试使用Int()(而不是as Int)转换它会发生什么?

标签: ios json dictionary swift


【解决方案1】:

问题是您要查找的数字不是 JSON 中的数字,而是字符串。所以试试这个:

let genreId = (item["id"] as String).toInt() // This casts the String to an Integer
                                             // Note that this is not Int but Int?

这是一个字符串:

【讨论】:

  • 解决了!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多