iOS Notes 32

iOS Notes 32 : How to convert JSON AnyObject to Custom Model?

Kuray Ogun
FreakyCoder Software Blog
1 min readJul 11, 2017

--

Hey,

JSON Parsing always an issue for any language. Here it is an example of converting JSON Object to Custom Model. In this example my Custom model is PhaseData, therefore you need to change it to your own one :)

Markdown:

do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonBody as! NSDictionary, options: .prettyPrinted)
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if decoded is [String:Any] {
let phaseData: PhaseData = PhaseData(JSON: decoded as! [String:Any])!
}
} catch {
print(error.localizedDescription)
}

Gist:

Do not forget, you need to handle decoded dictionary depends on your custom model. Do not stick with my example, this example my json object is an object, not an object array! Handle it, if you’re getting an array json object! :)

Have fun!

If you have any question, ask me :)

--

--