【发布时间】:2020-08-13 18:55:09
【问题描述】:
我是 Swift 语言的新手,我正在尝试在 Xcode 中构建一个简单的 JSON 解析应用程序。
这是我得到的错误: typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Date", intValue: nil)], debugDescription: "Expected to解码 Double 但找到了一个字符串/数据。”,基础错误:无))
这是一个要解析的链接: https://www.cbr-xml-daily.ru/daily_json.js
我有什么模型:(我使用https://app.quicktype.io 创建它)
struct Welcome: Codable {
var date, previousDate: Date
var previousURL: String
var timestamp: Date
var valute: [String: Valute]
enum CodingKeys: String, CodingKey {
case date = "Date"
case previousDate = "PreviousDate"
case previousURL = "PreviousURL"
case timestamp = "Timestamp"
case valute = "Valute"
}
}
struct Valute: Codable {
var id, numCode, charCode: String
var nominal: Int
var name: String
var value, previous: Double
enum CodingKeys: String, CodingKey {
case id = "ID"
case numCode = "NumCode"
case charCode = "CharCode"
case nominal = "Nominal"
case name = "Name"
case value = "Value"
case previous = "Previous"
}
}
下面是解析和解码的代码:
func request(urlString: String, completion: @escaping (Welcome?, Error?) -> Void) {
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Some error")
completion(nil, error)
return
} else {
guard let data = data else { return }
do {
let welcome = try JSONDecoder().decode(Welcome.self, from: data)
completion(welcome, nil)
} catch let jsonError {
print("Failed to decode JSON: \(jsonError)")
completion(nil, jsonError)
}
}
} .resume()
}
非常感谢您提供任何帮助/建议。
【问题讨论】:
标签: json swift jsondecoder