在Swift中获取JSON

1L3*_*L30 3 json nsjsonserialization swift

这是我获取JSON的代码,它与我在其他问题上找到的这个网址一起工作:http://binaenaleyh.net/dusor/.但是,当我使用它与这个网址:http://www.netcampus.fr/api/schools,它根本不起作用.我有一个错误说:"exc_breakpoint(code = exc_i386_bpt subcode = 0x0)"

我的代码是错误的,还是JSON数据?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    var myData:NSData = getJSON("http://www.netcampus.fr/api/schools")
    println(myData) // show me data
    var myDict:NSDictionary = parseJSON(myData)
    println(myDict)
}

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // error here
    return boardsDictionary
}
}
Run Code Online (Sandbox Code Playgroud)

Raf*_*fAl 6

parseJSON解析第二个JSON时,您的方法崩溃了.NSJSONSerialization将其内容映射到一个数组,你期待一个字典:

var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // error here
Run Code Online (Sandbox Code Playgroud)