JSON.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import Foundation
  2. protocol JSON: Codable {
  3. var rawJSON: String { get }
  4. init?(from: String)
  5. }
  6. extension JSON {
  7. var rawJSON: RawJSON {
  8. let encoder = JSONEncoder()
  9. encoder.outputFormatting = .prettyPrinted
  10. encoder.dateEncodingStrategy = .iso8601
  11. return String(data: try! encoder.encode(self), encoding: .utf8)!
  12. }
  13. init?(from: String) {
  14. let decoder = JSONDecoder()
  15. decoder.dateDecodingStrategy = .iso8601
  16. guard let data = from.data(using: .utf8),
  17. let object = try? decoder.decode(Self.self, from: data)
  18. else {
  19. return nil
  20. }
  21. self = object
  22. }
  23. }
  24. extension String: JSON {
  25. var rawJSON: String { self }
  26. init?(from: String) { self = from }
  27. }
  28. extension Double: JSON {}
  29. extension Int: JSON {}
  30. extension Bool: JSON {}
  31. extension Date: JSON {
  32. var rawJSON: String {
  33. let formatter = ISO8601DateFormatter()
  34. return formatter.string(from: self)
  35. }
  36. init?(from: String) {
  37. let dateFormatter = ISO8601DateFormatter()
  38. dateFormatter.formatOptions.insert(.withFractionalSeconds)
  39. let string = from.replacingOccurrences(of: "\"", with: "")
  40. if let date = dateFormatter.date(from: string) {
  41. self = date
  42. } else {
  43. return nil
  44. }
  45. }
  46. }
  47. typealias RawJSON = String
  48. extension Array: JSON where Element: JSON {}
  49. extension Dictionary: JSON where Key: JSON, Value: JSON {}