问题描述:

Below is my code snippet in ObjC

NSDictionary *json;

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"realstories" ofType:@"json"];

NSData *data = [NSData dataWithContentsOfFile:filePath];

json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

I've tried using its Siwft equivalent this way:

 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])

But I am stuck in error:

unexpectedly found nil while unwrapping an Optional value

Tried reading about it Here. But, could not get the error resolved!

网友答案:

Instead of JSONSerialization.jsonObject(with:) you are using NSKeyedUnarchiver, Also use native Data instead of 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)
                 }
            }
       }
   }
网友答案:

You can do it in the following way in swift 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 {

    }
}
相关阅读:
Top