-3

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!

Community
  • 1
  • 1
Vamshi Krishna
  • 979
  • 9
  • 19

4 Answers4

4

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
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1
// 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)
                 }
            }
       }
   }
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
1
if let data =  NSData(contentsOfFile:filePath!)
{
   if  let  json = NSKeyedUnarchiver.unarchiveObject(with: data) as? [AnyHashable:Any]() {
        // do something
    } else {
        print("There is an issue")
    }
  }
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

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 {

    }
}
KrishnaCA
  • 5,615
  • 1
  • 21
  • 31