斯威夫特Json错误
问题描述:
我试图从和服拉数据我遇到了错误。我的和服API的链接= https://www.kimonolabs.com/api/8dfvxr3a?apikey=5747a54d5ca762895b474cc224943240斯威夫特Json错误
和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()
}
答
在as Dictionary<String, String>
处抛出异常,因为您的JSON不是扁平字典。在你的情况下,你应该使用optional form of the type cast operator (as?
)将它投射到NSDictionary
或Dictionary<String,AnyObject>
。您不需要NSJSONReadingOptions.MutableContainers
,因为您只能从结果中读取。
jsonSonuc["count"]
是整数值,而不是字符串。您应该使用as? Int
将其转换为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)
}
}
谢谢@rintaro – 2015-12-07 18:47:32