Deserialize JSON / NSDictionary to Swift objects

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

    I am expanding upon Mohacs and Peter Kreinz's excellent answers just a bit to cover the array of like objects case where each object contains a mixture of valid JSON data types. If the JSON data one is parsing is an array of like objects containing a mixture of JSON data types, the do loop for parsing the JSON data becomes this.

    // Array of parsed objects
    var parsedObjects = [ParsedObject]()
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as [Dictionary]
        // Loop through objects
        for dict in json {
            // ParsedObject is a single instance of an object inside the JSON data
            // Its properties are a mixture of String, Int, Double and Bool
            let parsedObject = ParsedObject()
            // Loop through key/values in object parsed from JSON
            for (key, value) in json {
                // If property exists, set the value
                if (parsedObject.respondsToSelector(NSSelectorFromString(keyName))) {
                    // setValue can handle AnyObject when assigning property value
                    parsedObject.setValue(keyValue, forKey: keyName)
                }
            }
            parsedObjects.append(parsedObject)
        }
    } catch let error as NSError {
        print("Failed to load: \(error.localizedDescription)")
    }
    

提交回复
热议问题