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

时间:2014-08-09 07:55:10

标签: ios json dictionary swift

我已经解析了一个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。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

问题是你要查找的数字不是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