gpt4 book ai didi

ios - 无法在 Swift 4 中解码日期

转载 作者:可可西里 更新时间:2023-10-31 23:57:25 25 4
gpt4 key购买 nike

我目前正在尝试学习 Swift,但还没有走得很远,如果这是一个简单的问题,请原谅我;我已经为此工作了几个小时,但一直无法弄清楚。

我有一个名为 PersonCodable 类。在这个类中,我有一个名为 birthdateDate 属性。所以它看起来像这样:

class Person : Codable {
var birthdate: Date = Date()
var firstName: String = ""
var lastName: String = ""

enum CodingKeys : String, CodingKey {
case birthdate
case firstName = "first_name"
case lastName = "last_name"
}
}

我正在尝试解码我​​的 JSON:

[
{
"address": "302 N. 5th St.",
"base_64_image": null,
"birthdate": "2009-05-06T18:56:38.367",
"created": "2017-11-21T16:21:13",
"emergency_contact": "",
"emergency_contact_number": null,
"father_cell_number": null,
"father_home_number": null,
"father_name": null,
"first_name": "John",
"gender": 1,
"id": "d92fac59-66b9-49a5-9446-005babed617a",
"image_uri": null,
"is_inactive": false,
"last_name": "Smith",
"mother_cell_number": "1234567890",
"mother_home_number": "",
"mother_name": "His Mother",
"nickname": null,
"tenant_id": "9518352f-4855-4699-b0da-ecdc06470342",
"updated": "2018-01-20T02:11:45.9025023"
}
]

像这样:

// Fetch the data from the URL.
let headers: HTTPHeaders = [
"Accept": "application/json"
]

Alamofire.request(url, headers: headers).responseJSON { response in
if let data = response.data {
let decoder = JSONDecoder()

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let people = try! decoder.decode(Array<Person>.self, from: data)
}
}

但是,我总是得到同样的错误:

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 47", intValue: Optional(47)), App.Person.CodingKeys.birthdate], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil))

(“索引 47”显然不准确,因为那是我的实时 [和私有(private)] 数据)。

如果我从 Person 类中取出 birthdate 属性,一切都会按预期进行。

几个小时以来,我一直在谷歌搜索和尝试新事物,但无论我怎样尝试,它仍然无法正常工作。这里有人可以帮我吗?

最佳答案

它看起来像你的生日之一:

"birthdate": "2009-05-06T18:56:38.367",

包含毫秒。您的日期格式字符串:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

无法处理这个。您可以更改传入 JSON 中的 birthdate 字段,或将 dateFormat 字符串更改为:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

请注意,添加 .SSS 似乎会破坏非毫秒日期的格式化程序。我建议减少服务器端的毫秒数。


原回答如下:

我刚刚在 Playground 中尝试过,它似乎按预期工作:

class Person : Codable {
var birthdate: Date = Date()
var firstName: String = ""
var lastName: String = ""

enum CodingKeys : String, CodingKey {
case birthdate
case firstName = "first_name"
case lastName = "last_name"
}
}

var json: String = """
[
{
"birthdate": "2009-05-06T18:56:38",
"first_name": "John",
"last_name": "Smith"
}
]
"""

let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let people = try! decoder.decode(Array<Person>.self, from: json.data(using: .utf8, allowLossyConversion: false)!)

people 现在是这样的:

{birthdate "May 6, 2009 at 6:56 PM", firstName "John", lastName "Smith"}

要么我的代码与您的代码略有不同,要么可能需要一组不同的示例数据。

关于ios - 无法在 Swift 4 中解码日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49343500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com