【问题标题】:Objective - C to Swift : NSData with NSJSONSerialisationObjective - C to Swift : NSData with NSJSONSerialisation
【发布时间】:2017-02-15 06:56:10
【问题描述】:

下面是我在 ObjC 中的代码 sn-p

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

尝试阅读它Here。但是,无法解决错误!

【问题讨论】:

  • 你在哪一行面对这个
  • 第 -4 行(带有 NSKeyedUnarchiver 的 json)

标签: ios json swift


【解决方案1】:

你使用的是NSKeyedUnarchiver,而不是JSONSerialization.jsonObject(with:),也使用本机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
}

【讨论】:

    【解决方案2】:
    if let data =  NSData(contentsOfFile:filePath!)
    {
       if  let  json = NSKeyedUnarchiver.unarchiveObject(with: data) as? [AnyHashable:Any]() {
            // do something
        } else {
            print("There is an issue")
        }
      }
    

    【讨论】:

      【解决方案3】:
      // 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)
                       }
                  }
             }
         }
      

      【讨论】:

        【解决方案4】:

        在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 {
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2014-07-28
          • 2022-01-10
          • 1970-01-01
          • 2016-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-04
          • 2012-10-06
          相关资源
          最近更新 更多