Objective-C到Swift:使用NSJSONSerialisation的NSData

以下是我在ObjC中的代码片断

NSDictionary *json; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"realstories" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

我尝试过使用它的Siwft等价物:

  var json = [AnyHashable:Any]() let filePath: String? = Bundle.main.path(forResource: "realstories", ofType: "json") let data = NSData(contentsOfFile:filePath!) json = ((NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! NSDictionary) as! [AnyHashable:Any]) 

但是我陷入了错误:

 unexpectedly found nil while unwrapping an Optional value 

尝试阅读关于它在这里 。 但是,无法解决错误!

而不是JSONSerialization.jsonObject(with:)您正在使用NSKeyedUnarchiver ,也使用本机Data而不是NSData

  var json = [AnyHashable:Any]() if let filePath = Bundle.main.path(forResource: "realstories", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)), let dic = (try? JSONSerialization.jsonObject(with: data)) as? [AnyHashable:Any] { json = dic } 
 if let data = NSData(contentsOfFile:filePath!) { if let json = NSKeyedUnarchiver.unarchiveObject(with: data) as? [AnyHashable:Any]() { // do something } else { print("There is an issue") } } 
 // pass your file in fileName if let path = Bundle.main().pathForResource(fileNmae, ofType: "json") { do { if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) { if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary { print(jsonResult) } } } } 

你可以用下面的方式快速完成3

 if let fileurl:URL = Bundle.main.url(forResource: "realstories", withExtension: "json") { do { let data = try Data(contentsOf: fileurl) let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) }catch { } }