JSON.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 Decimal: JSON {}
  32. extension Date: JSON {
  33. var rawJSON: String {
  34. Formatter.iso8601withFractionalSeconds.string(from: self)
  35. }
  36. init?(from: String) {
  37. let dateFormatter = Formatter.iso8601withFractionalSeconds
  38. let string = from.replacingOccurrences(of: "\"", with: "")
  39. if let date = dateFormatter.date(from: string) {
  40. self = date
  41. } else {
  42. return nil
  43. }
  44. }
  45. }
  46. typealias RawJSON = String
  47. extension RawJSON {
  48. static let null = "null"
  49. }
  50. extension Array: JSON where Element: JSON {}
  51. extension Dictionary: JSON where Key: JSON, Value: JSON {}