斯威夫特杰森错误

时间:2014-10-31 02:06:52

标签: json swift

我试图从和服中提取数据我遇到了错误。我的和服api的链接= https://www.kimonolabs.com/api/8dfvxr3a?apikey=5747a54d5ca762895b474cc224943240

和Xcode错误

"thread 3: EXC_BREAKPOINT(code=EXC_1386_BPT,subcode0x0)"

如何修复此错误?

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var countLabel: UILabel!



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var ara: UITextField!
@IBAction func getir(sender: AnyObject) {

    araIMDB()
}

func araIMDB(){

        var urlYol = NSURL(string: "http://www.kimonolabs.com/api/8dfvxr3a?apikey=5747a54d5ca762895b474cc224943240")
        var oturum = NSURLSession.sharedSession()
        var task = oturum.dataTaskWithURL(urlYol!){

            data, response, error -> Void in
            if (error != nil){

                println(error)

            }
            var jsonError : NSError?
            var jsonSonuc  = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as Dictionary<String, String>
            if( jsonError != nil)
            {
                println(jsonError)
            }
            dispatch_async(dispatch_get_main_queue()){
                self.titleLabel.text = jsonSonuc["count"]
            }
          }
        task.resume()
    }

1 个答案:

答案 0 :(得分:1)

as Dictionary<String, String>抛出异常,因为您的JSON不是平面字典。在您的情况下,您应该使用optional form of the type cast operator (as?)将其投放到NSDictionaryDictionary<String,AnyObject>

您不需要NSJSONReadingOptions.MutableContainers,因为您只能从结果中读取。

jsonSonuc["count"]是整数值,而不是字符串。您应该使用Int将其投放到as? Int,然后将其转换为String

尝试:

        var jsonError: NSError?
        var jsonSonuc = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: &jsonError) as? NSDictionary
        if( jsonError != nil) {
            println(jsonError)
        }
        else if let count = jsonSonuc?["count"] as? Int {
            dispatch_async(dispatch_get_main_queue()){
                self.titleLabel.text = String(count)
            }
        }