我怎样才能parsing一个数组到json上的Swift?

我需要从json请求中获取值“maxtemp_c”,但它不起作用。

这是我所做的,当我尝试parsingJSON并且值为零时,它将会阻塞

//url of the json let url = URL(string: "http://api.apixu.com/v1/forecast.json?key=6cffef39633d4489a0e101339171811&q=Loria&days=3")! let taskfor = URLSession.shared.dataTask(with: url) { (data, response, error) in if error != nil { print("some error occured") } else { if error == nil { do{ let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] let forecast = jsonResult["forecast"] as? [String : AnyObject] // I would not recommend to use NSDictionary, try using Swift types instead guard let forecastday = forecast!["forecastday"] as? [[String:Any]] else { return } // Check for the weather parameter as an array of dictionaries and than excess the first array's description var finalArray:[Any] = [] //now I try to parse the json but the result is nil for result in forecastday { if let dict = result as? [String: Any], let forecastday = dict["day"] as? [String] { finalArray.append(forecastday) } } print(finalArray) }catch { print("JSON Preocessing failed") } } } } taskfor.resume() 

这是我必须parsing的json

 "forecast": { "forecastday": [ //this is the problem that the value is nil { "date": "2017-11-26", "date_epoch": 1511654400, "day": { "maxtemp_c": 7.3, //this is the value that I need 

看起来像“日”键包含字典不数组,只是从[String]更改为[String: Any] [String]

 for result in forecastday { if let dict = result as? [String: Any], let forecastday = dict["day"] as? [String: Any] { finalArray.append(forecastday) } } 

如果你只需要“maxtemp_c”数组,然后声明最终数组为[Double],并在最后添加一个检查“maxtemp_c”

 if let forecastday = forecast["forecastday"] as? [[String: Any]] { var finalArray: [Double] = [] for result in forecastday { if let dict = result as? [String: Any], let forecastday = dict["day"] as? [String: Any], let temp = forecastday["maxtemp_c"] as? Double { finalArray.append(temp) } } print(finalArray) } 

如果你想要[string]格式的“maxtemp_c”然后做

 finalArray.append(String(format: "%.1f", temp))