JSON.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import Foundation
  2. protocol JSON: Codable {
  3. var string: String { get }
  4. init?(from: String)
  5. }
  6. extension JSON {
  7. var string: String {
  8. String(data: try! JSONEncoder().encode(self), encoding: .utf8)!
  9. }
  10. init?(from: String) {
  11. guard let data = from.data(using: .utf8),
  12. let object = try? JSONDecoder().decode(Self.self, from: data)
  13. else {
  14. return nil
  15. }
  16. self = object
  17. }
  18. }
  19. extension String: JSON {
  20. var string: String { self }
  21. init?(from: String) { self = from }
  22. }
  23. extension Double: JSON {}
  24. extension Int: JSON {}
  25. extension Bool: JSON {}
  26. extension Date: JSON {
  27. var string: String {
  28. let formatter = ISO8601DateFormatter()
  29. formatter.formatOptions = [.withColonSeparatorInTimeZone]
  30. return formatter.string(from: self)
  31. }
  32. init?(from: String) {
  33. let dateFormatter = ISO8601DateFormatter()
  34. let string = from.replacingOccurrences(of: "\"", with: "")
  35. if let date = dateFormatter.date(from: string) {
  36. self = date
  37. } else {
  38. return nil
  39. }
  40. }
  41. }