简体   繁体   English

如何在JSONDecoder中处理空日期字符串

[英]How to handle an empty date string in JSONDecoder

The date parameter in my json can be empty(""). 我的json中的date参数可以为empty(“”)。 How to handle it in JSONDecoder? 如何在JSONDecoder中处理它?

The custom dateDecodingStrategy can only handle different format, but can't handle an empty value.(The date which formatter returned can't be optional). 自定义的dateDecodingStrategy只能处理不同的格式,但不能处理空值。(格式化程序返回的日期不能是可选的)。

When the date have an value, it will work perfectly. 当日期具有值时,它将很好地工作。 But when the date is "", it will crash. 但是当日期为“”时,它将崩溃。

decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
        let container = try decoder.singleValueContainer()
        let dateStr = try container.decode(String.self)

        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy"
        if let date = formatter.date(from: dateStr) {
            return date
        }
        formatter.dateFormat = "yyyy-MM-dd"
        if let date = formatter.date(from: dateStr) {
            return date
        }
        throw DateError.invalidDate
    })

Based on @vadian's comment, and supposing you are expecting user related data with a date of birth (dob) that may or may not have been declared by a certain user, what I did was the following 根据@vadian的评论,并假设您期望用户相关数据的出生日期(dob)可能由某个用户声明,也可能未由其声明。

public init(from decoder: Decoder) throws {
    //init other properties...
    do {
        self.dob = try container.decode(Date.self, forKey: .dob)
    } catch {
        self.dob = nil
    }
}

But again as per @vadian's comment, it would be better if the dob wasn't returned in the JSON response. 但是再次按照@vadian的评论,如果没有在JSON响应中返回dob会更好。 That way you wouldn't need the do/catch blocks at all. 这样,您根本不需要do / catch块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM