Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1505
情歌与酒
情歌与酒 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 19:09

    This way lets you get the user from a URL. It's parse the NSData to a NSDictionary and then to your NSObject.

    let urlS = "http://api.localhost:3000/"
    
    func getUser(username: Strung) -> User {
       var user = User()
       let url = NSURL(string: "\(urlS)\(username)")
       if let data = NSData(contentsOfURL: url!) {
         setKeysAndValues(user, dictionary: parseData(data))
       }
       return user
    }
    
    func setKeysAndValues (object : AnyObject, dictionary : NSDictionary)  -> AnyObject  {
        for (key, value) in dictionary {
            if let key = key  as? String, let value = value as? String {
                if (object.respondsToSelector(NSSelectorFromString(key))) {
                    object.setValue(value, forKey: key)
                }
            }
        }
        return object
    }
    
    func parseData (data : NSData)  -> NSDictionary  {
        var error: NSError?
        return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
    }
    
    0 讨论(0)
提交回复
热议问题