无法在Swift 4中解码日期

Tas*_*key 3 date ios swift swift4

我现在正在努力学习斯威夫特并且还没有走得太远,所以请原谅我,如果这是一个简单的问题; 我一直在努力工作几个小时,但一直无法解决这个问题.

我有一个Codable叫做的课Person.在这堂课上,我有一个Date叫做的属性birthdate.所以它看起来像这样:

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

而我正在尝试解码我​​的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"
    }
]
Run Code Online (Sandbox Code Playgroud)

像这样:

// 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

致命错误:'试试!' 表达式意外地引发了一个错误:Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath:[Foundation.(_ JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue:"Index 47",intValue:Optional(47)),App.Person.CodingKeys. birthdate],debugDescription:"日期字符串与格式化程序所期望的格式不匹配.",underlyingError:nil))

("索引47"显然不准确,因为这是我的[和私人]数据).

如果我参加了birthdate财产离开Person课堂上的一切工作正常.

我一直在谷歌搜索和尝试几个小时的新事物,无论我尝试什么,仍然无法让它工作.这里有人可以帮帮我吗?

Zun*_*ndo 7

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

"birthdate": "2009-05-06T18:56:38.367",
Run Code Online (Sandbox Code Playgroud)

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

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
Run Code Online (Sandbox Code Playgroud)

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

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
Run Code Online (Sandbox Code Playgroud)

请注意,添加.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)!)
Run Code Online (Sandbox Code Playgroud)

people现在在哪里:

{birthdate "May 6, 2009 at 6:56 PM", firstName "John", lastName "Smith"}
Run Code Online (Sandbox Code Playgroud)

我的代码和你的代码之间有一些微妙的不同,或者可能需要一组不同的示例数据.