JSON.swift 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. return formatter.string(from: self)
  30. }
  31. init?(from: String) {
  32. let dateFormatter = ISO8601DateFormatter()
  33. dateFormatter.formatOptions.insert(.withFractionalSeconds)
  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. }
  42. typealias RawJSON = String