OpenWeather API的JSON结果集未在Swift中返回主字典的值

时间:2019-01-22 19:19:58

标签: json swift api

我正在创建一个应用程序,该应用程序使用JSON从OpenWeather的API中提取天气信息。我嵌套了用于构建当前天气字符串的“ IF”语句。目标是构建一个字符串“当前天气是(描述),温度为(temp),风速为(wind)”。不幸的是,从“主”字典中检索“临时”值的if语句失败,而else语句失败,仅导致“当前天气为(描述)”。谁能告诉我我的代码是否正在执行某些操作,导致我无法将“主”字典中的“临时”值分配给

这是我的代码:

let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                        print(jsonResult)
                        if let description = ((jsonResult["weather"] as? NSArray)?[0] as? NSDictionary)?["description"] as? String {

                            print(description)
                            var weatherString = "Current weather is \(description)"
                            if let temp = ((jsonResult["main"] as? NSArray)?[0] as? NSDictionary)?["temp"] as? String {

                                weatherString += " with a temperature of \(temp)°"
                                if let wind = ((jsonResult["wind"] as? NSArray)?[0] as? NSDictionary)?["speed"] as? String {

                                    weatherString += " and a wind speed of \(wind)mph."

                                } else {

                                    weatherString += "."

                                }

                            } else {

                                weatherString += "."

                            }
                            DispatchQueue.main.sync(execute: {

                                self.weatherResult.text = weatherString

                            })

                        }

这是我从OpenWeather API获得的结果:

{
    base = stations;
    clouds =     {
        all = 75;
    };
    cod = 200;
    coord =     {
        lat = "37.78";
        lon = "-122.42";
    };
    dt = 1548179880;
    id = 5391959;
    main =     {
        humidity = 60;
        pressure = 1030;
        temp = "51.37";
        "temp_max" = "55.04";
        "temp_min" = "46.04";
    };
    name = "San Francisco";
    sys =     {
        country = US;
        id = 5817;
        message = "0.0042";
        sunrise = 1548170423;
        sunset = 1548206575;
        type = 1;
    };
    visibility = 16093;
    weather =     (
                {
            description = "broken clouds";
            icon = 04d;
            id = 803;
            main = Clouds;
        }
    );
    wind =     {
        deg = 10;
        speed = "6.93";
    };
}

1 个答案:

答案 0 :(得分:0)

您的代码中的错误是weather是一个数组([]),但是mainwind不是({})。 speedtempDouble,而不是String

尽管JSONSerialization太复杂,Decodable更简单,可读性更好,效率更高。

Openweathermap API发送始终一致的数据。

struct WeatherData : Decodable {  
    let weather : [Weather]
    let main : Main
    let wind : Wind
}

struct Main : Decodable { let temp : Double }

struct Weather : Decodable { let description: String }

struct Wind : Decodable { let speed : Double }

...

do {
   let result = try JSONDecoder().decode(WeatherData.self, from: urlContent)
   let description = result.weather.first?.description ?? "unknown"
   let temp = result.main.temp
   let wind = result.wind.speed
   DispatchQueue.main.async {
       self.weatherResult.text = "Current weather is \(description) with a temperature of \(temp) and a wind speed of \(wind) mph."
   }

} catch { print(error) }

注意:

  • 请勿在Swift中使用NSDictionary / NSArray,而应使用本机类型。
  • 切勿将JSONSerialization的结果强制转换为AnyObject,将其强制转换为期望的类型(数组,字典,字符串或数字类型)。
  • 请勿在Swift中使用.mutableContainers。该选项(以及.mutableLeaves)毫无意义。
  • 切勿sync进入主线程。一律做async.