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

前端 未结 8 1570
既然无缘
既然无缘 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:26

    It is a little verbose, but more flexible approach: wrap date with another Date class, and implement custom serialize methods for it. For example:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    class MyCustomDate: Codable {
        var date: Date
    
        required init?(_ date: Date?) {
            if let date = date {
                self.date = date
            } else {
                return nil
            }
        }
    
        public func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            let string = dateFormatter.string(from: date)
            try container.encode(string)
        }
    
        required public init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            let raw = try container.decode(String.self)
            if let date = dateFormatter.date(from: raw) {
                self.date = date
            } else {
                throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot parse date")
            }
        }
    }
    

    So now you are independent of .dateDecodingStrategy and .dateEncodingStrategy and your MyCustomDate dates will parsed with specified format. Use it in class:

    class User: Codable {
        var dob: MyCustomDate
    }
    

    Instantiate with

    user.dob = MyCustomDate(date)
    

提交回复
热议问题