ios - 如何在 swift 中解析并存储 json 字典中的整数值?

标签 ios json dictionary swift

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

这是我的代码:

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 中的数字,而是一个字符串。所以试试这个:

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

在这里你看到那是一个字符串:

Created with JSONView for Google Chrome

关于ios - 如何在 swift 中解析并存储 json 字典中的整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216470/

相关文章:

json - d3js json饼图

php - 如何创建 Laravel Eloquent 实体的空实例

java - Eureka 的 Springboot 错误,浏览器显示 xml 而不是 json

iphone - 如何从 iOS 上的 DICOM 文件中提取像素数据?

ios - 从合并信号中获取 RACTuple

objective-c - Objective C 能否在运行时确定调用者对象引用(反射)?

python - 如果它是 None,我如何在字典中设置一个值?

ios - 无法访问函数外定义的字典

android - 没有标签的离线世界卫星 map (Android)

objective-c - 如何在主线程外渲染 MKMapView?