如何将数组解析为Swift上的json?

时间:2017-11-26 09:18:49

标签: ios json swift

我需要取值" maxtemp_c"从json请求,但它没有工作。

这就是我所做的,当我尝试解析json并且值为nil时它会阻塞

//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()

这是我必须解析的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

1 个答案:

答案 0 :(得分:0)

看起来像" day" key包含Dictionary not Array,只需将其从[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)
}

如果你想" maxtemp_c"以[String]格式然后执行

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