在编程方面,我是新手,我试图在Alamofire和SwiftyJSON的帮助下解析一个JSON,如果JSON文件很简单,我就没有问题,工作也很好,但是当我有类似于字典的->字典-> ->数组->字典时,问题就开始了,所以我有以下代码:
func performCYesterdayWeatherFetch(forSelectedCity: String)
{
let properString = forSelectedCity.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
Alamofire.request("http://api.apixu.com/v1/history.json?key=MY_KEY&q=\(properString!)&dt=2016-10-20").responseJSON { (response) -> Void in
guard response.result.isSuccess else
{
print("Error while fetching remote rooms: \(response.result.error)")
return
}
guard let json = response.result.value as? JSON,
let forecastJson = json["forecast"].dictionary else
{
print("YESTERDAY PROBLEM")
return
}
for item in (forecastJson["forecastday"]?.arrayValue)!
{
let day = item["day"].dictionaryObject
guard let yesterdayTempCels = day?["avgtemp_c"] as! Double?,
let yesterdayTempFahr = day?["avgtemp_f"] as! Double? else
{
return
}MY_KEY -真的是我的钥匙,问题不在于我没有输入这个键。
它总是进入其他地方:
guard let json = response.result.value as? JSON,
let forecastJson = json["forecast"].dictionary else
{
print("YESTERDAY PROBLEM")
return
}它们的结果JSON看起来是这样的:我需要瘦的是avgtemp_c和avgtemp_f

我做错了什么?
发布于 2016-10-28 13:46:45
这里有一个解决方案,您甚至不需要SwiftyJSON来获取这些值。
let properString = forSelectedCity.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
Alamofire.request("http://api.apixu.com/v1/history.json?key=MY_KEY&q=\(properString!)&dt=2016-10-20").responseJSON { (response) -> Void
guard let json = response.result.value as? [String: Any],
let forecastDictionary = json["forecast"] as? [String: Any],
let forecastDayArray = forecastDictionary["forecastday"] as? [[String: Any]] else {
print("YESTERDAY PROBLEM")
return
}
for item in forecastDayArray {
guard let day = item["day"] as? [String: Any],
let yesterdayTempCels = day["avgtemp_c"] as? Double,
let yesterdayTempFahr = day["avgtemp_f"] as? Double else {
return
}
// Here you should have the values that you need
}
}https://stackoverflow.com/questions/40306047
复制相似问题