Swift's JSONDecoder with multiple date formats in a JSON string?

前端 未结 8 1568
既然无缘
既然无缘 2020-12-14 06:48

Swift\'s JSONDecoder offers a dateDecodingStrategy property, which allows us to define how to interpret incoming date strings in accordance with a

8条回答
  •  青春惊慌失措
    2020-12-14 07:28

    Please try decoder configurated similarly to this:

    lazy var decoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
            let container = try decoder.singleValueContainer()
            let dateStr = try container.decode(String.self)
            // possible date strings: "2016-05-01",  "2016-07-04T17:37:21.119229Z", "2018-05-20T15:00:00Z"
            let len = dateStr.count
            var date: Date? = nil
            if len == 10 {
                date = dateNoTimeFormatter.date(from: dateStr)
            } else if len == 20 {
                date = isoDateFormatter.date(from: dateStr)
            } else {
                date = self.serverFullDateFormatter.date(from: dateStr)
            }
            guard let date_ = date else {
                throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateStr)")
            }
            print("DATE DECODER \(dateStr) to \(date_)")
            return date_
        })
        return decoder
    }()
    

提交回复
热议问题