Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

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.

Slide 3

Slide 3 text

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.

Slide 4

Slide 4 text

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)

Slide 5

Slide 5 text

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.map(JSONObject: dict) let model: PersonCodable? = dict.convert() Or

Slide 6

Slide 6 text

Let’s see some code

Slide 7

Slide 7 text

DataMapper KeyedDataMapper DataItem Extension Custom Operator 
 <<- High Level Diagram of Data Flow & Interaction

Slide 8

Slide 8 text

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.

Slide 9

Slide 9 text

Thank you