Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1534
情歌与酒
情歌与酒 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

    SWIFT 4 Update


    Since you give a very simple JSON object the code prepared for to handle that model. If you need more complicated JSON models you need to improve this sample.

    Your Custom Object

    class Person : NSObject {
        var name : String = ""
        var email : String = ""
        var password : String = ""
    
        init(JSONString: String) {
            super.init()
    
            var error : NSError?
            let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    
            let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) as NSDictionary
    
            // Loop
            for (key, value) in JSONDictionary {
                let keyName = key as String
                let keyValue: String = value as String
    
                // If property exists
                if (self.respondsToSelector(NSSelectorFromString(keyName))) {
                    self.setValue(keyValue, forKey: keyName)
                }
            }
            // Or you can do it with using 
            // self.setValuesForKeysWithDictionary(JSONDictionary)
            // instead of loop method above
        }
    }
    

    And this is how you invoke your custom class with JSON string.

    override func viewDidLoad() {
        super.viewDidLoad()
        let jsonString = "{ \"name\":\"myUser\", \"email\":\"user@example.com\", \"password\":\"passwordHash\" }"
        var aPerson : Person = Person(JSONString: jsonString)
        println(aPerson.name) // Output is "myUser"
    }
    

提交回复
热议问题