Deserializer.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // Created by zhouzhuo on 7/7/16.
  17. //
  18. import Foundation
  19. public extension HandyJSON {
  20. /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and converts it to a Model
  21. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer
  22. static func deserialize(from dict: NSDictionary?, designatedPath: String? = nil) -> Self? {
  23. return deserialize(from: dict as? [String: Any], designatedPath: designatedPath)
  24. }
  25. /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and converts it to a Model
  26. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer
  27. static func deserialize(from dict: [String: Any]?, designatedPath: String? = nil) -> Self? {
  28. return JSONDeserializer<Self>.deserializeFrom(dict: dict, designatedPath: designatedPath)
  29. }
  30. /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model
  31. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer
  32. static func deserialize(from json: String?, designatedPath: String? = nil) -> Self? {
  33. return JSONDeserializer<Self>.deserializeFrom(json: json, designatedPath: designatedPath)
  34. }
  35. }
  36. public extension Array where Element: HandyJSON {
  37. /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`,
  38. /// this method converts it to a Models array
  39. static func deserialize(from json: String?, designatedPath: String? = nil) -> [Element?]? {
  40. return JSONDeserializer<Element>.deserializeModelArrayFrom(json: json, designatedPath: designatedPath)
  41. }
  42. /// deserialize model array from NSArray
  43. static func deserialize(from array: NSArray?) -> [Element?]? {
  44. return JSONDeserializer<Element>.deserializeModelArrayFrom(array: array)
  45. }
  46. /// deserialize model array from array
  47. static func deserialize(from array: [Any]?) -> [Element?]? {
  48. return JSONDeserializer<Element>.deserializeModelArrayFrom(array: array)
  49. }
  50. }
  51. public class JSONDeserializer<T: HandyJSON> {
  52. /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and map it to a Model
  53. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil
  54. public static func deserializeFrom(dict: NSDictionary?, designatedPath: String? = nil) -> T? {
  55. return deserializeFrom(dict: dict as? [String: Any], designatedPath: designatedPath)
  56. }
  57. /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and map it to a Model
  58. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil
  59. public static func deserializeFrom(dict: [String: Any]?, designatedPath: String? = nil) -> T? {
  60. var targetDict = dict
  61. if let path = designatedPath {
  62. targetDict = getInnerObject(inside: targetDict, by: path) as? [String: Any]
  63. }
  64. if let _dict = targetDict {
  65. return T._transform(dict: _dict) as? T
  66. }
  67. return nil
  68. }
  69. /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to Model
  70. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil
  71. public static func deserializeFrom(json: String?, designatedPath: String? = nil) -> T? {
  72. guard let _json = json else {
  73. return nil
  74. }
  75. do {
  76. let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments)
  77. if let jsonDict = jsonObject as? NSDictionary {
  78. return self.deserializeFrom(dict: jsonDict, designatedPath: designatedPath)
  79. }
  80. } catch let error {
  81. InternalLogger.logError(error)
  82. }
  83. return nil
  84. }
  85. /// Finds the internal dictionary in `dict` as the `designatedPath` specified, and use it to reassign an exist model
  86. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil
  87. public static func update(object: inout T, from dict: [String: Any]?, designatedPath: String? = nil) {
  88. var targetDict = dict
  89. if let path = designatedPath {
  90. targetDict = getInnerObject(inside: targetDict, by: path) as? [String: Any]
  91. }
  92. if let _dict = targetDict {
  93. T._transform(dict: _dict, to: &object)
  94. }
  95. }
  96. /// Finds the internal JSON field in `json` as the `designatedPath` specified, and use it to reassign an exist model
  97. /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil
  98. public static func update(object: inout T, from json: String?, designatedPath: String? = nil) {
  99. guard let _json = json else {
  100. return
  101. }
  102. do {
  103. let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments)
  104. if let jsonDict = jsonObject as? [String: Any] {
  105. update(object: &object, from: jsonDict, designatedPath: designatedPath)
  106. }
  107. } catch let error {
  108. InternalLogger.logError(error)
  109. }
  110. }
  111. /// if the JSON field found by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`,
  112. /// this method converts it to a Models array
  113. public static func deserializeModelArrayFrom(json: String?, designatedPath: String? = nil) -> [T?]? {
  114. guard let _json = json else {
  115. return nil
  116. }
  117. do {
  118. let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments)
  119. if let jsonArray = getInnerObject(inside: jsonObject, by: designatedPath) as? [Any] {
  120. return jsonArray.map({ (item) -> T? in
  121. return self.deserializeFrom(dict: item as? [String: Any])
  122. })
  123. }
  124. } catch let error {
  125. InternalLogger.logError(error)
  126. }
  127. return nil
  128. }
  129. /// mapping raw array to Models array
  130. public static func deserializeModelArrayFrom(array: NSArray?) -> [T?]? {
  131. return deserializeModelArrayFrom(array: array as? [Any])
  132. }
  133. /// mapping raw array to Models array
  134. public static func deserializeModelArrayFrom(array: [Any]?) -> [T?]? {
  135. guard let _arr = array else {
  136. return nil
  137. }
  138. return _arr.map({ (item) -> T? in
  139. return self.deserializeFrom(dict: item as? NSDictionary)
  140. })
  141. }
  142. }
  143. fileprivate func getInnerObject(inside object: Any?, by designatedPath: String?) -> Any? {
  144. var result: Any? = object
  145. var abort = false
  146. if let paths = designatedPath?.components(separatedBy: "."), paths.count > 0 {
  147. var next = object as? [String: Any]
  148. paths.forEach({ (seg) in
  149. if seg.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" || abort {
  150. return
  151. }
  152. if let _next = next?[seg] {
  153. result = _next
  154. next = _next as? [String: Any]
  155. } else {
  156. abort = true
  157. }
  158. })
  159. }
  160. return abort ? nil : result
  161. }