【发布时间】:2015-10-19 22:02:09
【问题描述】:
我正在使用我的 REST Web 服务来获取我想要的 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 个元素的数组,它们是字典。
然后我尝试使用 NSJSONSerialization 解析 JSON。
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).
这对我来说似乎很清楚,但我只是不知道如何解决它。
我的目标是从我自己的类中创建“事件”对象。
【问题讨论】:
-
json是一个字典数组。有了json["name"],您就假设它是一本字典,但事实并非如此。那么json[0]['name"]? -
你试过 SwiftyJSON 吗?