Swift:JSONDecoder 从 API 返回 nil

syd*_*yds 2 json decoder swift

目前正在通过一个从 OpenWeatherMap API 获取和解码数据的应用程序工作,目前除了让解码器返回一些东西之外,我已经让一切正常工作。目前,解码器返回 nil,但是,我从 API 调用中获取数据字节。我不完全确定可能是什么问题。我已经根据层次结构设置了 ViewModel 结构。OPW API JSON 数据似乎是字典 key:value 对集合类型的格式,键被引号括起来,是不是我的解码器因为引号没有找到必要的信息?

获取和解码 API 调用...

@IBAction func saveCityButtonPressed() {

    if let city = cityNameTextField.text {
        let weatherURL = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=8bad8461edbaf3ff50aa2f2fd8ad8a71&units=imperial")!

        let weatherResource = Resource<WeatherViewModel>(url: weatherURL) { data in
            let weatherVM = try? JSONDecoder().decode(WeatherViewModel.self, from: data)
            return weatherVM
        }
        Webservice().load(resource: weatherResource) { result in
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

视图模型

struct WeatherListViewModel {
private var weatherViewModels = [WeatherViewModel]()
}

struct WeatherViewModel: Decodable {
let name: String
let main: TemperatureViewModel
}

struct TemperatureViewModel: Decodable {
let temp: Double
let temp_min: Double
let temp_max: Double
}
Run Code Online (Sandbox Code Playgroud)

JSON 数据示例:

{
    "coord":{
       "lon":-0.13,
       "lat":51.51
    },
    "weather":[
        {
             "id":300,
             "main":"Drizzle",
             "description":"light intensity drizzle","icon":"09d"
        }
    ],
    "base":"stations",
    "main":{
        "temp":280.32,
        "pressure":1012,
        "humidity":81,
        "temp_min":279.15,
        "temp_max":281.15
     },
     "visibility":10000,
     "wind":{
         "speed":4.1,
         "deg":80
     },
     "clouds":{
         "all":90
     },
     "dt":1485789600,
     "sys":{
         "type":1,
         "id":5091,
         "message":0.0103,
         "country":"GB",
         "sunrise":1485762037,
         "sunset":1485794875
     },
     "id":2643743,
     "name":"London",
     "cod":200
 }
Run Code Online (Sandbox Code Playgroud)

小智 10

通过生成JSONDecoder().decode可选 ( try?)的结果,您可以确保nil在解码出错时得到结果。您可以通过实施适当的 catch 块来快速捕获与解码相关的问题。例如:

do {
    let decoder = JSONDecoder()
    let messages = try decoder.decode(WeatherViewModel.self, from: data)
    print(messages as Any)
} catch DecodingError.dataCorrupted(let context) {
    print(context)
} catch DecodingError.keyNotFound(let key, let context) {
    print("Key '\(key)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
    print("Value '\(value)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context) {
    print("Type '\(type)' mismatch:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch {
    print("error: ", error)
}
Run Code Online (Sandbox Code Playgroud)

不是对您问题的直接回答,但肯定会减少其他人了解解码哪一部分出错的时间。

  • 这应该是答案!感谢您抽出宝贵时间做出如此全面的答复。 (3认同)

mat*_*att 2

您的 WeatherViewModel 属性city是一个字符串,但您的 JSON 中没有"city"键。