Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1531
情歌与酒
情歌与酒 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条回答
  •  萌比男神i
    2020-11-29 19:04

    There's a great example by Apple for deserializing JSON with Swift 2.0

    The trick is to use the guard keyword and chain the assignments like so:

    init?(attributes: [String : AnyObject]) {
        guard let name = attributes["name"] as? String,
            let coordinates = attributes["coordinates"] as? [String: Double],
            let latitude = coordinates["lat"],
            let longitude = coordinates["lng"],
            else {
                return nil
        }
        self.name = name
        self.coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    

    I personally prefer native parsing vs any 3rd party, as it is transparent and magic-less. (and bug less?)

提交回复
热议问题