以下是我的代码片段
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
尝试在这里阅读有关它。但是,无法解决错误!
而不是JSONSerialization.jsonObject(with:)
您使用的是NSKeyedUnarchiver
,也使用本机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
}
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)
}
}
}
}
您可以在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 {
}
}