本文介绍了目标-从C到Swift:带有NSJSONSerialisation的NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我在ObjC中的代码段
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];
我已经尝试过以这种方式使用它的Siwft:
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])
但是我陷入了错误:
unexpectedly found nil while unwrapping an Optional value
尝试阅读有关内容此处.但是,无法解决错误!
Tried reading about it Here. But, could not get the error resolved!
推荐答案
您使用的是NSKeyedUnarchiver
而不是JSONSerialization.jsonObject(with:)
,还请使用本机的Data
而不是NSData
.
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
}
这篇关于目标-从C到Swift:带有NSJSONSerialisation的NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!