Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1514
情歌与酒
情歌与酒 2020-11-29 18:43

Is there a way to properly deserialize a JSON response to Swift objects resp. using DTOs as containers for fixed JSON APIs?

Something similar to http://james.newtonk

13条回答
  •  失恋的感觉
    2020-11-29 18:59

    I recommend that you use code generation (http://www.json4swift.com) to create native models out of the json response, this will save your time of parsing by hand and reduce the risk of errors due to mistaken keys, all elements will be accessible by model properties, this will be purely native and the models will make more sense rather checking the keys.

    Your conversion will be as simple as:

    let userObject = UserClass(userDictionary)
    print(userObject!.name)
    

提交回复
热议问题