Skip to content

Instantly share code, notes, and snippets.

@MarioIannotta
Created September 25, 2017 18:57
Show Gist options
  • Save MarioIannotta/493ef058c41922d68d492a3e1a0c71f1 to your computer and use it in GitHub Desktop.
Save MarioIannotta/493ef058c41922d68d492a3e1a0c71f1 to your computer and use it in GitHub Desktop.
import Foundation
extension String {
var stringToDateCustomMethod: Date {
return Date()
}
}
extension KeyedDecodingContainer {
subscript<T: Decodable>(key: KeyedDecodingContainer.Key) -> T? {
return try? decode(T.self, forKey: key)
}
}
struct Post: Decodable {
var id: Int?
var userId: Int?
var date: Date?
var title: String?
var subtitle: String?
enum CustomJsonKeys: String, CodingKey {
case id
case userId
case date
case title = "__title"
case subtitle = "__subtitle"
}
init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: CustomJsonKeys.self)
self.id = decoderContainer[.id]
self.userId = decoderContainer[.userId]
self.date = (decoderContainer[.date] as String?)?.stringToDateCustomMethod
self.title = decoderContainer[.title]
self.subtitle = decoderContainer[.subtitle]
}
}
let postInfoJson = """
{
"userId": 12212,
"id": 112371239,
"date": "22/11/1222",
"__title": "Swift 4 Codable: tips and tricks",
"__subtitle": "Many of you may agree with me when I say the Codable protocol is the best Swift 4 feature, here are some of my impressions about it."
}
"""
let decoder = JSONDecoder()
if let jsonData = postInfoJson.data(using: .utf8) {
do {
let post = try decoder.decode(Post.self, from: jsonData)
print(post)
} catch let error as NSError {
print(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment