JSONDictionaryWrapper.swift 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import Foundation
  2. public typealias JSONDictionary = [String: Any]
  3. public struct JSONDictionaryWrapper: Codable {
  4. public let jsonDictionary: JSONDictionary
  5. public enum CodingKeys: String, CodingKey {
  6. case jsonDictionary
  7. }
  8. public init(jsonDictionary: JSONDictionary) {
  9. self.jsonDictionary = jsonDictionary
  10. }
  11. public init(from decoder: Decoder) throws {
  12. let container = try decoder.container(keyedBy: CodingKeys.self)
  13. let data = try container.decode(Data.self, forKey: CodingKeys.jsonDictionary)
  14. let object = try JSONSerialization.jsonObject(
  15. with: data,
  16. options: []
  17. )
  18. guard let jsonDictionary = object as? JSONDictionary else {
  19. throw StorageError.decodingFailed
  20. }
  21. self.jsonDictionary = jsonDictionary
  22. }
  23. public func encode(to encoder: Encoder) throws {
  24. var container = encoder.container(keyedBy: CodingKeys.self)
  25. let data = try JSONSerialization.data(
  26. withJSONObject: jsonDictionary,
  27. options: []
  28. )
  29. try container.encode(data, forKey: CodingKeys.jsonDictionary)
  30. }
  31. }