Objective - C to Swift : NSData with NSJSONSerialisation
Posted
技术标签:
【中文标题】Objective - 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) 【参考方案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
【讨论】:
以上是关于Objective - C to Swift : NSData with NSJSONSerialisation的主要内容,如果未能解决你的问题,请参考以下文章