JSON.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import Foundation
  2. @dynamicMemberLookup protocol JSON: Codable {
  3. var rawJSON: String { get }
  4. init?(from: String)
  5. }
  6. private func encoder() -> JSONEncoder {
  7. let encoder = JSONEncoder()
  8. encoder.outputFormatting = .prettyPrinted
  9. encoder.dateEncodingStrategy = .iso8601
  10. return encoder
  11. }
  12. private func decoder() -> JSONDecoder {
  13. let decoder = JSONDecoder()
  14. decoder.dateDecodingStrategy = .iso8601
  15. return decoder
  16. }
  17. extension JSON {
  18. var rawJSON: RawJSON {
  19. String(data: try! encoder().encode(self), encoding: .utf8)!
  20. }
  21. init?(from: String) {
  22. guard let data = from.data(using: .utf8),
  23. let object = try? decoder().decode(Self.self, from: data)
  24. else {
  25. return nil
  26. }
  27. self = object
  28. }
  29. var dictionaryRepresentation: [String: Any]? {
  30. guard let data = rawJSON.data(using: .utf8),
  31. let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
  32. else {
  33. return nil
  34. }
  35. return dict
  36. }
  37. subscript(dynamicMember string: String) -> Any? {
  38. dictionaryRepresentation?[string]
  39. }
  40. }
  41. extension String: JSON {
  42. var rawJSON: String { self }
  43. init?(from: String) { self = from }
  44. }
  45. extension Double: JSON {}
  46. extension Int: JSON {}
  47. extension Bool: JSON {}
  48. extension Decimal: JSON {}
  49. extension Date: JSON {
  50. init?(from: String) {
  51. let dateFormatter = Formatter.iso8601withFractionalSeconds
  52. let string = from.replacingOccurrences(of: "\"", with: "")
  53. if let date = dateFormatter.date(from: string) {
  54. self = date
  55. } else {
  56. return nil
  57. }
  58. }
  59. }
  60. typealias RawJSON = String
  61. extension RawJSON {
  62. static let null = "null"
  63. }
  64. extension Array: JSON where Element: JSON {}
  65. extension Dictionary: JSON where Key: JSON, Value: JSON {}
  66. extension Dictionary where Key == String {
  67. var rawJSON: RawJSON? {
  68. guard let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) else { return nil }
  69. return RawJSON(data: data, encoding: .utf8)
  70. }
  71. }
  72. enum JSONCoding {
  73. static var encoder: JSONEncoder {
  74. let encoder = JSONEncoder()
  75. encoder.outputFormatting = .prettyPrinted
  76. encoder.dateEncodingStrategy = .customISO8601
  77. return encoder
  78. }
  79. static var decoder: JSONDecoder {
  80. let decoder = JSONDecoder()
  81. decoder.dateDecodingStrategy = .customISO8601
  82. return decoder
  83. }
  84. }