Safe Dynamic JSON Casts In Swift

独自空忆成欢 提交于 2019-12-24 13:12:17

问题


I suspect that I am not quite grokking Swift 1.2, and I need to RTFM a bit more.

I'm working on a Swift app that reads JSON data from a URI.

If the JSON data is bad, or nonexistent, no issue. The JSON object never instantiates.

However, if the JSON data is good JSON, but not what I want, the object instantiates, but contains a structure that is not what I'm looking for, I get a runtime error.

I looked at using Swift's "RTTI" (dynamicType), but that always returns "<Swift.AnyObject>", no matter what the data is.

I want the JSON to be a specific format: An array of Dictionaries:

[[String:String]]! JSON: [{"key":"value"},{"key","value"},{"Key":"value"}]

If I feed it a single element:

{"Key":"value"}

The routine I have tries to cast it, and that fails.

I want to test the JSON object to make sure that it has a structure I want before casting.

    if(nil != inData) {
        let rawJSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(inData, options: nil, error: nil)
        println("Type:\(rawJSONObject.dynamicType)")
        if(nil != rawJSONObject) {
            // THE LINE BELOW BLOWS UP IF I FEED IT "BAD/GOOD" JSON:
            let jsonObject: [[String:String]]! = rawJSONObject as! [[String:String]]!
            // I NEED TO TEST IT BEFORE DOING THE CAST
            if((nil != jsonObject) && (0 < jsonObject.count)) {
                let jsonDictionary: [String:String] = jsonObject[0]
                if("1" == jsonDictionary["semanticAdmin"]) { // We have to have the semantic admin flag set.
                    let testString: String!  = jsonDictionary["versionInt"]

                    if(nil != testString) {
                        let version = testString.toInt()

                        if(version >= self.s_minServerVersion) {    // Has to be a valid version for us to pay attention.
                            self.serverVersionAsInt = version!
                        }
                    }
                }
            }
        }
    }

My question is, is there a good way to test an NSJSONSerialization response for the structure of the JSON before uwinding/casting it?

I feel as if this question may be closer to what I need, but I am having trouble "casting" it to my current issue.


回答1:


You can use safe unwrapping to test the type of your raw object, for example:

if let jsonObject = rawJSONObject as? [[String:String]] {
    // jsonObject is an array of dictionaries
} else if let jsonObject = rawJSONObject as? [String:String] {
    // jsonObject is a dictionary
    // you can conform it as you wish, for example put it in an array
} else {
    // fail, rawJSONObject is of another type
}

Currently, your code crashes because of the forced unwrapping, with !, of values that will be nil if the cast fails.



来源:https://stackoverflow.com/questions/31100138/safe-dynamic-json-casts-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!