![](/img/trans.png)
[英]How to handle dynamic keys from a JSON response using jsonDecoder?
[英]How to handle an empty date string in JSONDecoder
我的json中的date参数可以为empty(“”)。 如何在JSONDecoder中处理它?
自定义的dateDecodingStrategy只能处理不同的格式,但不能处理空值。(格式化程序返回的日期不能是可选的)。
当日期具有值时,它将很好地工作。 但是当日期为“”时,它将崩溃。
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
})
根据@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
}
}
但是再次按照@vadian的评论,如果没有在JSON响应中返回dob会更好。 这样,您根本不需要do / catch块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.