【问题标题】:decoder.decode setting valid iso8601 date as nil [duplicate]decoder.decode 将有效的 iso8601 日期设置为 nil [重复]
【发布时间】: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 ..
  • 你用的是什么代码?
  • 您问题中的代码进行了一些小的调整,以使其在我的操场上工作。是的,你配置的格式化程序。
  • 你能提供你的工作代码吗?

标签: ios swift xcode


【解决方案1】:

据我所知,这是 XCode 调试器中的一个错误。我的代码没有问题。

使用快速监视/本地窗口,PublishedDateGmt 的值始终为零,这让我疯狂地尝试调试它。

但是,如果您将值打印出来,您会看到该值确实存在。

查看截图:

如果有人有任何其他解释我想知道...

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2012-08-25
    • 2016-01-03
    相关资源
    最近更新 更多