handle JSON to Object conversion in a scalable way. • Design a system that can handle Codable and ObjectMapper both and can be scaled for further types. • Use Generics to map response values. • Use Operator and function overloading.
Business logic. • To encapsulate JSON parsing logic and make it scalable. • To work around Codable’s inability to handle keyPath mapping. • To easily convert Dictionary to Objects.
handles parsing of JSON to Object • KeyedDataMapper This component extracts data from the JSON dictionary based on keyPath and passes the data forward to DataMapper to parse. • DataItem This is a type alias typealias DataItem = [String: Any] • KeyedDataItem This is a tupple type alias typealias KeyedDataItem = (data: DataItem?, key: String)
Any] = [ "name": "demo", "age": 20, ] if !JSONSerialization.isValidJSONObject(dict as Any) { return } do { let data = try JSONSerialization.data(withJSONObject: dict as Any, options: .prettyPrinted) let model: PersonCodable? = try JSONDecoder().decode(PersonCodable.self, from: data) // do something with model } catch (let error) { print(error) // handle parsing error } } struct PersonCodable: Codable { var name: String var age: Int } Which we will change to let model: PersonCodable? = DataMapper<PersonCodable>.map(JSONObject: dict) let model: PersonCodable? = dict.convert() Or
scalable, we can add more parsing frameworks by adding/overloading a few functions. • We can hook up the parsing framework to API framework by adding an additional layer to give objects directly. • Makes the parsing code Unit testable.