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

Efficient JSON to Object Parsing

Eeb061c8b2816b771920da1b3e7904a3?s=47 Swift India
February 29, 2020

Efficient JSON to Object Parsing

Eeb061c8b2816b771920da1b3e7904a3?s=128

Swift India

February 29, 2020
Tweet

Transcript

  1. Efficient JSON to Object parsing by, Lab Singh
 https://github.com/lab-nit-s/CustomMapper

  2. 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.
  3. 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.
  4. 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)
  5. 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
  6. Let’s see some code

  7. DataMapper KeyedDataMapper DataItem Extension Custom Operator 
 <<- High Level

    Diagram of Data Flow & Interaction
  8. 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.
  9. Thank you