Response+HandyJSON.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Response+HandyJSON.swift
  3. // o2app
  4. //
  5. // Created by 刘振兴 on 2017/8/24.
  6. // Copyright © 2017年 zone. All rights reserved.
  7. //
  8. import Foundation
  9. import Moya
  10. import HandyJSON
  11. // MARK: - Response扩展
  12. public extension Response {
  13. /// 整个 Data Model
  14. ///
  15. /// - Parameter type:
  16. /// - Returns:
  17. public func mapObject<T: HandyJSON>(_ type: T.Type) -> T? {
  18. guard let dataString = String.init(data: self.data, encoding: .utf8),
  19. let object = JSONDeserializer<T>.deserializeFrom(json: dataString)
  20. else {
  21. return nil
  22. }
  23. return object
  24. }
  25. /// 制定的某个 Key 对应的模型
  26. ///
  27. /// - Parameters:
  28. /// - type:
  29. /// - designatedPath:
  30. /// - Returns:
  31. public func mapObject<T: HandyJSON>(_ type: T.Type ,designatedPath: String) -> T?{
  32. guard let dataString = String(data: self.data, encoding: .utf8),
  33. let object = JSONDeserializer<T>.deserializeFrom(json: dataString, designatedPath: designatedPath)
  34. else {
  35. return nil
  36. }
  37. return object
  38. }
  39. /// Data 对应的 [Model]
  40. ///
  41. /// - Parameter type:
  42. /// - Returns:
  43. public func mapArray<T: HandyJSON>(_ type: T.Type) -> [T?]? {
  44. guard let dataString = String(data: self.data, encoding: .utf8),
  45. let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString)
  46. else {
  47. return nil
  48. }
  49. return object
  50. }
  51. /// Data 某个Key 下对应的 的 [Model]
  52. public func mapArray<T: HandyJSON>(_ type: T.Type ,designatedPath: String ) -> [T?]? {
  53. guard let dataString = String(data: self.data, encoding: .utf8),
  54. let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString , designatedPath: designatedPath)
  55. else {
  56. return nil
  57. }
  58. return object
  59. }
  60. }