我有一个使用JSONDecoder()解析的json文件。但是,我收到了iso-8601格式的日期类型的可变时间戳记(“ yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX”),但是在我看来,我想以自定义格式显示它: “ dd / mm / yy HH:mm:ss”。
我编写了以下代码,但时间戳记为nil,并且我认为时间戳记为iso-8601格式时,“ date”不是正确的类型:
错误json:typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath:[_JSONKey(stringValue:“索引 0“,intValue:0),CodingKeys(stringValue:” timestamp“,intValue: nil)],debugDescription:“预期对Double进行解码,但发现 字符串/数据。”,underlyingError:nil))
swift4
import UIKit
enum Type : String, Codable {
case organizational, planning
}
// structure from json file
struct News: Codable{
let type: Type
let timestamp: Date //comes in json with ISO-8601-format
let title: String
let message: String
enum CodingKeys: String, CodingKey { case type, timestamp, title, message}
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yy HH:mm:ss" // change format ISO-8601 to dd/MM/yy HH:mm:ss
return formatter
}()
var dateString : String {
return dateFormatter.string(from:timestamp) // take timestamp variable of type date and make it a string -> lable.text
}
}
答案 0 :(得分:2)
在解码Date
时,解码器默认需要UNIX时间戳(Double
),这就是错误消息告诉您的内容。
但是,如果您添加Date
,则实际上可以将ISO8601字符串解码为decoder.dateDecodingStrategy = .iso8601
,但这只会在毫秒内内仅解码标准ISO8601字符串。
有两种选择:
添加带有formatted
的{{1}} dateDecodingStrategy
。
DateFormatter
将let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
try decoder.decode(...
声明为
timestamp
并使用let timestamp: String
中的两个格式化程序或两个日期格式来回转换字符串。