Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Efficient JSON to Object Parsing

Swift India
February 29, 2020

Efficient JSON to Object Parsing

Swift India

February 29, 2020
Tweet

More Decks by Swift India

Other Decks in Technology

Transcript

  1. Our Discussion today. • We will see how to efficiently

    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.
  2. Why this approach? • To de-couple JSON parsing with our

    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.
  3. The Components • DataMapper
 This is the main component that

    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)
  4. General Usage of Codable func parse() { let dict: [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
  5. Advantages • Completely de-coupled Parsing system. • The system is

    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.