使用JSON解析数据并在Swift框架中使用它并在计算之后将其发送到应用程序以进行显示。
我尝试了以下代码来打开一个Json文件并读取它,但由于nil返回到路径,因此总是以“无效文件路径”结束。
if let path = NSBundle.mainBundle().pathForResource("furnitures", ofType: "json") {
print(path)
do {
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
do {
let jsonResultDict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let furnTyp : [NSDictionary] = jsonResultDict["furnTypes"] as? [NSDictionary] {
for furType: NSDictionary in furnTyp {
for (name,value) in furType {
if name as! String == "sofa" {
print(value)
}
}
}
}
} catch {
"exception at NSJSONSerialization"
}
} catch {
print("exception at NSData")
}
}
else {
print("Invalid file Path")
}
此外,我尝试使用以下代码获取路径并将其传递给NSData以获取文件的内容,最后在NSData处出现异常
let file = "furnitures.json"
var jsonFilePath: String! = nil
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
//path will be stored here
jsonFilePath = dir.stringByAppendingPathComponent(file);
print(jsonFilePath) // printing the file path
}
如此友好地帮助我解决这个问题。
提前致谢