首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SWIFT4.1 JSON到Struct然后到不同日期的数组

SWIFT4.1 JSON到Struct然后到不同日期的数组
EN

Stack Overflow用户
提问于 2018-06-11 09:44:30
回答 1查看 55关注 0票数 0

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

代码语言:javascript
复制
[{"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"}...

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

代码语言:javascript
复制
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对象?如果没有,我如何实现所需的功能,或者,是否有更好的方法来做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-11 09:57:14

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

代码语言:javascript
复制
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
}

声明startDateTimestopDateTimeDate,并将DateFormatter传递为dateDecodingStrategy

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50794762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档