iOS – 在Swift中用NSJSONSerializationparsingJSON字典

我正在使用我的REST Webservice来获取我想要的JSON数据,这个工作原理和打印:

[{ "name": "Event1", "genre": "Party", "subtitle": "subtitle1", "startDate": "2015-10-10", "location": "Anywhere" }, { "name": "Event2", "genre": "Party", "subtitle": "subtitle2", "startDate": "2015-10-10", "location": "Anywhere" }] 

所以这似乎是一个包含2个元素的字典的数组。

然后我试图用NSJSONSerializationparsingJSON。

 let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject] if let name = json["name"] as? [String]{ print(name) } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } 

我得到这个错误:

 Could not cast value of type '__NSCFArray' (0x1096c1ae0) to 'NSDictionary' (0x1096c1d60). 

这似乎很清楚,但我只是不知道如何解决它。

我的目标是从我自己的class级创build“事件”对象。

反序列化的结果将是一个数组:

 let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { let dataArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray for event in dataArray { print(event) } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") }