let json = """
{
"id": 1,
"title": "Title",
"thumbnail": "https://www.sample-videos.com/img/Sample-jpg-image-500kb.jpg",
"date": "2014-07-15"
}
""".data(using: .utf8)!
public struct NewsCodable: Codable {
public let id: Int
public let title: String
public let thumbnail: PercentEncodedUrl
public let date: MyDate
}
public struct PercentEncodedUrl: Codable {
public let url: URL
public init(from decoder: Decoder) throws {
let urlString = try decoder.singleValueContainer().decode(String.self)
guard
let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL.init(string: encodedUrlString) else {
throw PercentEncodedUrlError.url(urlString)
}
self.url = url
}
public enum PercentEncodedUrlError: Error {
case url(String)
}
}
Date decoding has plenty of support in JSONDecoder
public struct MyDate: Codable {
public let date: Date
public init(from decoder: Decoder) throws {
let dateString = try decoder.singleValueContainer().decode(String.self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let date = dateFormatter.date(from: dateString) else {
throw MyDateError.date(dateString)
}
self.date = date
}
public enum MyDateError: Error {
case date(String)
}
}
let decoder = JSONDecoder()
let news = try! decoder.decode(NewsCodable.self, from: json)