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