decoder.decode 将有效的 iso8601 日期设置为 nil [英] decoder.decode setting valid iso8601 date as nil

查看:49
本文介绍了decoder.decode 将有效的 iso8601 日期设置为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,我有以下代码...

In Swift, I have the following code...

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 示例.

And this is an example of the JSON.

{
         "PartitionKey": "test1",
        "RowKey": "123",
        "PublishedDateGmt": "2019-06-29T17:27:46Z",
        "Title": "Test Title"
    }

除 PublishedDateGmt 之外的所有内容都会序列化.序列化它没有任何错误,除非它给我零.

Everything except PublishedDateGmt serializes. I do not get any errors serializing it except it gives me nil.

我什至尝试过下面的代码,但日期转换失败.(在下面的例子中,我确实得到了转换失败而不是 nil 是 Article 对象中属性的最终结果).

I've even tried the code below but the date conversion fails. (In the examples below, I do get conversion failures instead of nil being the final result of the property in the Article object).

// let dateFormatter = DateFormatter()
        //dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"//2019-06-29T17:27:46Z
            //decoder.dateDecodingStrategy = .formatted(dateFormatter)

除了被序列化为 nil 的 PublishedDateGmt 日期字段外,所有内容都正确序列化.

Everything serializes properly except for the PublishedDateGmt date field which gets serialized as nil.

这里返回的json数据的一个日期示例是:2019-06-29T17:27:46Z

An example of a date here from the json data returned is:2019-06-29T17:27:46Z

这应该是一个有效的 iso8601 日期,对吧?

This should be a valid iso8601 date, right?

其他所有内容都正确转换为 Article 对象,并且编码密钥设置正确.

Everything else is converting properly into the Article object and the coding keys are set up correctly.

推荐答案

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

This was a bug, as far as I can tell, in the XCode debugger. There is nothing wrong with my code.

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

Using the quick watch / locals window the value for PublishedDateGmt was always nil which was driving me crazy trying to debug it.

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

However, if you print the value out, you see that value is actually there.

查看截图:

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

If anyone has any other explanation I'd like to know...

这篇关于decoder.decode 将有效的 iso8601 日期设置为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆