Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import Foundation
  2.  
  3. extension String {
  4. var stringToDateCustomMethod: Date {
  5. return Date()
  6. }
  7. }
  8.  
  9. extension KeyedDecodingContainer {
  10. subscript<T: Decodable>(key: KeyedDecodingContainer.Key) -> T? {
  11. return try? decode(T.self, forKey: key)
  12. }
  13. }
  14.  
  15. struct Post: Decodable {
  16. var id: Int?
  17. var userId: Int?
  18. var date: Date?
  19. var title: String?
  20. var subtitle: String?
  21.  
  22. enum CustomJsonKeys: String, CodingKey {
  23. case id
  24. case userId
  25. case date
  26. case title = "__title"
  27. case subtitle = "__subtitle"
  28. }
  29.  
  30. init(from decoder: Decoder) throws {
  31. let decoderContainer = try decoder.container(keyedBy: CustomJsonKeys.self)
  32.  
  33. self.id = decoderContainer[.id]
  34. self.userId = decoderContainer[.userId]
  35. self.date = (decoderContainer[.date] as String?)?.stringToDateCustomMethod
  36. self.title = decoderContainer[.title]
  37. self.subtitle = decoderContainer[.subtitle]
  38. }
  39. }
  40.  
  41. let postInfoJson = """
  42. {
  43. "userId": 12212,
  44. "id": 112371239,
  45. "date": "22/11/1222",
  46. "__title": "Swift 4 Codable: tips and tricks",
  47. "__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."
  48. }
  49. """
  50.  
  51. let decoder = JSONDecoder()
  52.  
  53. if let jsonData = postInfoJson.data(using: .utf8) {
  54. do {
  55. let post = try decoder.decode(Post.self, from: jsonData)
  56. print(post)
  57. } catch let error as NSError {
  58. print(error)
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement