安全动态 JSON 施放 Swift

Safe Dynamic JSON Casts In Swift

我怀疑我对Swift 1.2 不是很了解,我需要多了解一下RTFM。

我正在开发一个 Swift 应用程序,它从 URI 读取 JSON 数据。

如果 JSON 数据错误或不存在,则没有问题。 JSON 对象从不实例化。

但是,如果 JSON 数据很好 JSON,但不是我想要的,对象实例化,但包含的结构不是我要找的,我得到一个运行时错误。

我查看了使用 Swift 的 "RTTI"(动态类型),但无论数据是什么,它总是 returns“”。

我希望 JSON 为特定格式:字典数组:

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

如果我给它一个元素:

{"Key":"value"}

我的例程尝试施放它,但失败了。

我想测试 JSON 对象以确保它在转换前具有我想要的结构。

    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!
                        }
                    }
                }
            }
        }
    }

我的问题是,有没有什么好的方法可以测试JSON之前JSON结构的NSJSON序列化响应呢?

我觉得 this question 可能更接近我的需要,但我遇到了问题 "casting" 我目前的问题。

您可以使用安全解包来测试原始对象的类型,例如:

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
}

目前,您的代码因 ! 强制解包而崩溃,如果转换失败,这些值将为 nil。