最佳答案
我试图获取一个 JSON 响应并将结果存储在一个变量中。在之前的 Swift 版本中,我已经有了这个代码的版本,直到 Xcode 8的 GM 版本发布。我看了一些关于 StackOverflow 的类似文章: Swift 2解析 JSON-无法下标类型为‘ AnyObject’的值和 Swift 3中的 JSON 解析。
然而,这里传达的想法似乎并不适用于这种情况。
如何正确解析 Swift 3中的 JSON 响应? 在 Swift 3中 JSON 的读取方式有什么变化吗?
下面是有问题的代码(它可以在操场上运行) :
import Cocoa
let url = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
if let url = NSURL(string: url) {
if let data = try? Data(contentsOf: url as URL) {
do {
let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
//Store response in NSDictionary for easy access
let dict = parsedData as? NSDictionary
let currentConditions = "\(dict!["currently"]!)"
//This produces an error, Type 'Any' has no subscript members
let currentTemperatureF = ("\(dict!["currently"]!["temperature"]!!)" as NSString).doubleValue
//Display all current conditions from API
print(currentConditions)
//Output the current temperature in Fahrenheit
print(currentTemperatureF)
}
//else throw an error detailing what went wrong
catch let error as NSError {
print("Details of JSON parsing error:\n \(error)")
}
}
}
编辑: 下面是 print(currentConditions)
之后 API 调用的结果示例
["icon": partly-cloudy-night, "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precipIntensity": 0, "windSpeed": 6.04, "summary": Partly Cloudy, "ozone": 321.13, "temperature": 49.45, "dewPoint": 41.75, "apparentTemperature": 47, "windBearing": 332, "cloudCover": 0.28, "time": 1480846460]