IOS 10 objectForKey("key") 兼容性

IOS 10 objectForKey("key") compatibility

我正在研究我的应用程序与 IOS10 的兼容性,但在执行此代码时遇到问题:

if let results = NSJSONSerialization.TryJSONObjectWithData(data, options: []) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["results"] as? NSMutableArray {
        print(" here");

                for i in 0 ..< networkPosts.count {
                    let post:Post = Post(postDictionary: networkPosts[i] as! NSDictionary, context: (UIApplication.sharedApplication().delegate as! 

AppDelegate).coreDataHelper.managedObjectContext);
}
        }
    }

我可以看到结果,所以 JSON 没问题,但是在我看不到字典的结果键之后。 "Here" 从未打印在我的控制台上。我已经尝试制作一个断点并且同样它不会通过那里。 我也尝试过 .objectForKey("key") 但结果相同:/

有人可以帮我吗?

如果我用results["results"] as? [[String: Any]]

然后

networkPosts[i] as! NSDictionary always fails

在使用 TryJSONObjectWithData 使数组和字典可变时,您应该使用 NSJSONReadingMutableContainers 选项

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/c/tdef/NSJSONReadingOptions

使用 Playground 测试的示例 Swift 3:

let jsonString = "{\"name\":\"Mattia\",\"iosDevices\":[\"iPhone6\",\"iPad Air 2\",\"iPhone6+\"]} 
let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false)!

if let results = try JSONSerialization.jsonObject(with: jsonData, options: [.mutableContainers]) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["iosDevices"] as? NSMutableArray {
        print(" here");
    }
}