Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement