我正在调用一个API,它返回约会的JSON结果。示例:
[{"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!)然后,self.appointments数组在UICollectionView中使用。所有这些都很好。但是,我想将collectionView分割成基于不同StartDates的部分,每个节都有一个头。
我尝试过创建一个辅助数组,但是在我的JSON中,以及在约会数组中,StartDateTime的值是一个字符串,而不是日期。我可以循环遍历约会数组,并将appointment.StartDateTime的值转换为date对象,并添加到一个新的数组中,该数组应该允许我选择不同的日期,但是我无法拆分原始约会数组,因为该值仍然是一个字符串。
是否有可能在调用解码时将其转换为date对象?如果没有,我如何实现所需的功能,或者,是否有更好的方法来做到这一点?
发布于 2018-06-11 09:57:14
首先,使用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
}声明startDateTime和stopDateTime为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)https://stackoverflow.com/questions/50794762
复制相似问题