我有一个复杂的JSON数据。 我该如何解析这些数据? 我试过了,但它不起作用。
我需要一个带对象的词典(id,time ...)。但是如何通过“1,......”? 我怎样才能开始和结束时间?
"data": {
"1":[
{"id":6524612,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
"2":[
{
"id":6524613,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
我的错误在哪里?
let broadcastTask = broadcastSession.dataTaskWithRequest(broadcastRequest) { (data, response, error) -> Void in
if error != nil {
print(error.debugDescription)
} else {
do {
let broadcastDict = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? Dictionary<String, AnyObject>
if let results = broadcastDict!["data"] as? [Dictionary<String, AnyObject>] {
for obj in results {
let broadcast = Broadcast(broadcastDict: obj)
self.broadcastList.append(broadcast)
}
//Main UI thread
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
} catch {
}
}
}
broadcastTask.resume()
init(broadcastDict: Dictionary<String, AnyObject>) {
if let category = broadcastDict["id"] as? Int {
self.id = id
}
...
}
答案 0 :(得分:1)
如果我正确理解了这个问题: 第一个问题似乎是你试图将“数据”字典转换为字典数组。这将始终失败,因为您的数据对象是字典而不是数组。
一旦你纠正了这个问题,你的循环就会遇到麻烦。试试这个:
for (key, value) in results {
let broadcast = Broadcast(broadcastDict: value)
self.broadcastList.append(broadcast)
}
现在您正在发送您的Broadcast
对象所期望的字典。