【发布时间】:2020-02-26 09:33:19
【问题描述】:
在 Swift 中,我有以下代码...
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let articles = try decoder.decode(Articles.self, from: data)
class Article: Codable {
init(_ PartitionKey : String?, RowKey : String?, PublishedDateGmt:Date?, Title:String?) {
self.PartitionKey = PartitionKey
self.RowKey = RowKey
self.PublishedDateGmt = PublishedDateGmt
self.Title = Title
}
enum CodingKeys: String, CodingKey {
// include only those that you want to decode/encode
case PartitionKey
case PublishedDateGmt
case Title
case RowKey
}
let RowKey: String?
let PartitionKey: String?
let PublishedDateGmt: Date?
let Title: String?
}
这是 JSON 的一个示例。
{
"PartitionKey": “test1”,
"RowKey": “123”,
"PublishedDateGmt": "2019-06-29T17:27:46Z",
"Title": “Test Title”
}
除 PublishedDateGmt 之外的所有内容都会序列化。序列化它没有任何错误,除非它给我 nil。
我什至尝试过下面的代码,但日期转换失败。 (在下面的示例中,我确实得到了转换失败,而不是 nil 是 Article 对象中属性的最终结果)。
// let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"//2019-06-29T17:27:46Z
//decoder.dateDecodingStrategy = .formatted(dateFormatter)
除了 PublishedDateGmt 日期字段被序列化为 nil 之外,所有内容都正确序列化。
这里从返回的json数据中的一个日期示例是:2019-06-29T17:27:46Z
这应该是一个有效的 iso8601 日期,对吧?
其他所有内容都正确转换为 Article 对象,并且编码键设置正确。
【问题讨论】:
-
您的代码与您的自定义日期格式化程序配合得很好
-
你的意思是使用我写的自定义而不依赖iso8601?对我来说,当我使用我的自定义日期格式化程序时,我得到一个转换错误,而不是仅仅在属性中设置 nil ..
-
你用的是什么代码?
-
您问题中的代码进行了一些小的调整,以使其在我的操场上工作。是的,你配置的格式化程序。
-
你能提供你的工作代码吗?