【发布时间】:2018-01-03 14:57:54
【问题描述】:
我是新手,在理解这一切如何运作时遇到了一些麻烦。
我有这个结构:
struct EventDetail:Decodable {
let EventName: String
let EventInformation: String
let EventStartDate: Date
let EventEndDate: Date
}
还有这个函数来下载 json:
func downloadJSON(completed: @escaping () -> ()) {
let url = URL(string: "http://someurl.php")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.events = try JSONDecoder().decode([EventDetail].self, from: data!)
DispatchQueue.main.async {
completed()
}
}catch {
print(error)
}
}
}.resume()
}
}
这是我得到的 JSON 错误:
JSON 错误 typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), Cosplay_Life.EventDetail.(CodingKeys in _52013DB7ECF3BE1EBFBF83BE6BA8F9E9) , debugDescription: "预期解码 Double 但找到了一个字符串/数据。",底层错误: nil))
如果EventStartDate 和EventEndDate 是字符串,这一切似乎都有效,但我确实希望将其作为Date,因为稍后我将使用日期字段对数据进行排序。下载的值格式为 "yyyy-MM-dd" eks: "2017-02-25" 我在做什么错?
【问题讨论】:
-
寻找
dateDecodingStrategy的JSONDecoder,以及DateFormatter。 -
您可以编辑您的问题以包含 JSON 吗?