【发布时间】:2018-04-12 23:24:48
【问题描述】:
我在为以下 JSON 创建公共结构时遇到了麻烦。我正在尝试提取温度和湿度。我试图提取以下 JSON,但我认为我识别每个变量的方式有问题。
这是 JSON:
{"coord":{"lon":-82.26,"lat":27.76},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"base":"stations","main":{"temp":66.24,"pressure":1021,"humidity":63,"temp_min":62.6,"temp_max":69.8},"visibility":16093,"wind":{"speed":8.05,"deg":80},"clouds":{"all":90},"dt":1523500500,"sys":{"type":1,"id":726,"message":0.0051,"country":"US","sunrise":1523531237,"sunset":1523577156},"id":420006939,"name":"Brandon","cod":200}
这是结构
public struct Page: Decodable {
private enum CodingKeys : String, CodingKey {
case coord = "coord", weather = "weather", mainz = "main", visibility = "visibility", wind = "wind", clouds = "clouds", dt = "dt", sys = "sys", id = "id", name = "name", cod = "cod"}
let coord: String
let weather: [String]
let mainz: String
let visibility: Int
let wind: String
let clouds: String
let dt: Int
let sys: String
let id: Int
let name: String
let cod: Int
public struct Main: Decodable {
private enum CodingKeys : String, CodingKey {
case temp = "temp", pressure = "pressure",humidity = "humidity", temp_min = "temp_min", temp_max = "temp_max"
}
let temp: Int
let pressure: Int
let humidity: Int
let temp_min: Int
let temp_max: Int
}
...以及我正在使用解码的代码...
// Make the POST call and handle it in a completion handler
let task = session.dataTask(with: components.url!, completionHandler: {(data, response, error) in
guard let data = data else { return }
do
{
let result = try JSONDecoder().decode(Page.self, from: data)
for main in result.mainz {
print(main.humidity)
}
}catch
{print("Figure it out")
}
})
task.resume()
【问题讨论】:
-
首先你需要知道如何阅读 JSON。查看 JSON 中的第一件事:
"coord":{"lon":-82.26,"lat":27.76}。好吧,那个叫做"coord"的东西不是字符串;这是一本字典。但是您将coord输入为字符串。所以这永远不会成功。 ——我可以继续,但你是需要继续的人。想想每件事的类型。
标签: json swift4 decode xcode9.2