JSONDecoder+Extensions.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Foundation
  2. /// Convert json string, dictionary, data to Codable objects
  3. public extension JSONDecoder {
  4. /// Convert json string to Codable object
  5. ///
  6. /// - Parameters:
  7. /// - string: Json string.
  8. /// - type: Type information.
  9. /// - Returns: Codable object.
  10. /// - Throws: Error if failed.
  11. static func decode<T: Codable>(_ string: String, to type: T.Type) throws -> T {
  12. guard let data = string.data(using: .utf8) else {
  13. throw StorageError.decodingFailed
  14. }
  15. return try decode(data, to: type.self)
  16. }
  17. /// Convert json dictionary to Codable object
  18. ///
  19. /// - Parameters:
  20. /// - json: Json dictionary.
  21. /// - type: Type information.
  22. /// - Returns: Codable object
  23. /// - Throws: Error if failed
  24. static func decode<T: Codable>(_ json: [String: Any], to type: T.Type) throws -> T {
  25. let data = try JSONSerialization.data(withJSONObject: json, options: [])
  26. return try decode(data, to: type)
  27. }
  28. /// Convert json data to Codable object
  29. ///
  30. /// - Parameters:
  31. /// - json: Json dictionary.
  32. /// - type: Type information.
  33. /// - Returns: Codable object
  34. /// - Throws: Error if failed
  35. static func decode<T: Codable>(_ data: Data, to type: T.Type) throws -> T {
  36. return try JSONDecoder().decode(T.self, from: data)
  37. }
  38. }