用Alamofire问题解析JSON

时间:2016-10-28 13:23:01

标签: ios json parsing dictionary swift3

我是swift和编程的新手,我试图在Alamofire和SwiftyJSON的帮助下解析JSON,如果JSON文件很简单,我没有问题并且工作正常,但是当我有像Dictionary这样的东西时 - >字典 - >数组 - >字典,问题开始,所以我有以下代码:

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

JSON PIC

我做错了什么?

1 个答案:

答案 0 :(得分:1)

这里有一个解决方案,您甚至不需要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
    }
}