Swift 4.1 JSON到Struct然后到不同日期的数组

时间:2018-06-11 09:44:30

标签: json swift4.1

我正在调用一个返回JSON约会结果的API。示例:

[{"DiarySummary":"Test appointment","DiaryDescription":"Test","DiaryId":"62","EventNo":"","EventTypeId":"","StartDateTime":"07/06/2018 09:00:51","StopDateTime":"07/06/2018 21:00:51","DayHalfDay":"0","AgentGroupName":"DEV","AgentInitials":"AC","AgentId":"5","OwnerShortName":"","OwnerLongName":"","AbsenceTypeDescription":"Working From Home","AbsenceTypeId":"15"}...

我使用解码函数将代码映射到代码中的结构:

struct DiaryAppointment: Decodable {
let DiarySummary: String?
let DiaryDescription: String?
let DiaryId: String?
let EventNo: String?
let EventTypeId: String?
let StartDateTime: String?
let StopDateTime: String?
let DayHalfDay: String?
let AgentGroupName: String?
let AgentInitials: String?
let AgentId: String?
let OwnerShortName: String?
let OwnerLongName: String?
let AbsenceTypeDescription: String?
let AbsenceTypeId: String?
}

self.appointments = try JSONDecoder().decode([DiaryAppointment].self, from: data!)

然后在UICollectionView中使用self.appointments数组。所有这一切都很好。但是,我想将collectionView拆分为基于不同StartDates的部分,每个部分都有一个标题。

我试过创建一个辅助数组,但是我的JSON中的StartDateTime的值因此在我的约会数组中是一个字符串而不是日期。我可以遍历约会数组并将appointment.StartDateTime的值转换为日期对象并添加到一个新数组,这应该允许我选择不同的日期,但我将无法拆分原始约会数组因为该值仍然是一个字符串。

是否有可能在调用解码时将​​其转换为日期对象?如果没有,我如何实现所需的功能,或者,有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

首先使用CodingKeys获取小写的变量名称,并尽可能多地声明属性:

struct DiaryAppointment: Decodable {
    private enum CodingKeys: String, CodingKey {
        case diarySummary = "DiarySummary", diaryDescription = "DiaryDescription", diaryId = "DiaryId"
        case eventNo = "EventNo", eventTypeId = "EventTypeId", startDateTime = "StartDateTime"
        case stopDateTime = "StopDateTime", dayHalfDay = "DayHalfDay", agentGroupName = "AgentGroupName"
        case agentInitials = "AgentInitials", agentId = "AgentId", ownerShortName = "OwnerShortName"
        case ownerLongName = "OwnerLongName", absenceTypeDescription = "AbsenceTypeDescription", absenceTypeId = "AbsenceTypeId"
    }
    let diarySummary, diaryDescription, diaryId, eventNo, eventTypeId: String
    let startDateTime, stopDateTime: Date
    let dayHalfDay, agentGroupName, agentInitials, agentId: String
    let ownerShortName, ownerLongName, absenceTypeDescription, absenceTypeId: String
}

startDateTimestopDateTime声明为Date,并将DateFormatter作为dateDecodingStrategy

传递
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(dateFormatter)