【发布时间】:2015-02-18 18:55:09
【问题描述】:
我正在努力遍历从 Web 服务调用返回的字典值数组。
我已经实现了以下代码,但我似乎在运行时遇到了崩溃。
我还想将结果存储到自定义结构中。真的很难实现这一点,到目前为止,这里的答案还没有奏效。如果有人能够提供帮助,将不胜感激。
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
if let list = nudgesJSONResult["nudges"] as? [[String:String]] {
for nudgeDict in list {
let location = nudgeDict["location"]
println(location)
}
}
}
})
task.resume()
}
【问题讨论】:
-
它在哪里崩溃? JSON 数据是什么样的?也许它是一个 JSON array 而不是 dictionary?在那种情况下,
as NSDictionary会崩溃(而且这个问题每隔一天就会出现在这里……) -
您在可选绑定中将
nudgesJSONResult["nudges"]分配给字典——nudges和字典数组list(如果让...)。这可能是一些问题的开始,但正如 Martin R 指出的那样,问题是什么并不清楚。 -
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。跨度>
-
JSON 数据可以在这里找到:whatthefoot.co.uk/NUDGE/nudges.php。当我 println(nudgesJSONResult) 时,JSON 在 xcode 控制台中输出正常。难以访问嵌套在 API 中的值
标签: arrays json swift dictionary struct