我有一个天气预报JSON,我使用Swift 4中的新方法来序列化结构的JSON,但问题是当我想打印JSON时我会收到这个:
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预计会解码数组,但会找到一个字典。”,underlyingError:nil))
这是我的JSON代码:
struct currently : Decodable {
let summary : String?
let temperature : Float?
let timezone : String
init(json : [String : Any]) {
summary = json["summary"] as? String ?? ""
temperature = json["temperature"] as? Float ?? -1
timezone = json["timezone"] as? String ?? ""
}
}
以下是获取JSON的代码:
let jsonURL = "https://api.darksky.net/forecast/[code]/\(ViewController.latitude),\(ViewController.longitude)"
guard let url = URL(string : jsonURL) else {
return
}
URLSession.shared.dataTask(with: url) { (data , response , error) in
guard let data = data else {return}
do {
let currentlies = try JSONDecoder().decode(currently.self , from : data)
print(currentlies.timezone)
print(currentlies.summary)
print(currentlies.temperature)
}
catch {
print(error)
}
}.resume()
答案 0 :(得分:2)
您可以这样使用:
struct Response : Decodable {
let timezone : String
let currently: Currently
}
struct Currently: Decodable {
let summary: String
let temperature: Double
}
let jsonURL = "https://api.darksky.net/forecast/[code]/\(ViewController.latitude),\(ViewController.longitude)"
guard let url = URL(string : jsonURL) else {
return
}
URLSession.shared.dataTask(with: url) { (data , response , error) in
guard let data = data else {return}
do {
let currentlies = try JSONDecoder().decode(Response.self , from : data)
print(currentlies.timezone)
print(currentlies.currently.summary)
print(currentlies.currently.temperature)
} catch {
print(error)
}
}.resume()