在swift中从复杂的JSON中获取数据



我有一个复杂的JSON数据。如何解析此数据?我试过了,但没用。

我需要一个带object(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
        }
...
}

如果我正确理解问题:第一个问题似乎是您试图将"数据"字典转换为字典数组。这总是会失败,因为您的数据对象是字典而不是数组。

一旦你纠正了这个问题,你的循环就会遇到麻烦。试试这个:

for (key, value) in results {
    let broadcast = Broadcast(broadcastDict: value)
    self.broadcastList.append(broadcast)
}

现在,您正在发送Broadcast对象所期望的字典。

相关内容

  • 没有找到相关文章

最新更新