Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用SwiftyJSON从文件中检索数据_Json_Swift_Swifty Json - Fatal编程技术网

如何使用SwiftyJSON从文件中检索数据

如何使用SwiftyJSON从文件中检索数据,json,swift,swifty-json,Json,Swift,Swifty Json,我在文件系统中添加了一个JSON文件,其中的数据结构如下: {“DDD”:“3D系统公司”、“MMM”:“3M公司”、“WBAI”: “500.com有限公司”、“WUBA”:“58.com有限公司”、“AHC”:“A.H.贝洛” “公司”、“ATEN”:“A10网络公司”、“AAC”:“AAC控股公司”, “航空公司”:“AAR公司”} 我的文件名是stockDict.json,我试图使用以下代码从中检索数据: let jsonFilePath:NSString = NSBundle.main

我在文件系统中添加了一个JSON文件,其中的数据结构如下:

{“DDD”:“3D系统公司”、“MMM”:“3M公司”、“WBAI”: “500.com有限公司”、“WUBA”:“58.com有限公司”、“AHC”:“A.H.贝洛” “公司”、“ATEN”:“A10网络公司”、“AAC”:“AAC控股公司”, “航空公司”:“AAR公司”}

我的文件名是
stockDict.json
,我试图使用以下代码从中检索数据:

let jsonFilePath:NSString = NSBundle.mainBundle().pathForResource("stockDict", ofType: "json")!
        let jsonData:NSData = NSData.dataWithContentsOfMappedFile(jsonFilePath as String) as! NSData
        let error:NSError?
        let json = JSON(jsonData)

        println(json[0][0].string)
但当它打印出来时,我得到的只是
nil
。我的代码有什么问题

如果您有任何建议,我们将不胜感激。

您是否尝试过

let json = JSON(data: jsonData) // Note: data: parameter name
println(json["DDD"].string)

我没有代表对此发表评论,但是这个答案在iOS 8中已经被弃用了,特别是在下面的部分

.dataWithContentsOfMappedFile
XCode告诉我

'dataWithContentsOfMappedFile' was deprecated in iOS 8.0: Use +dataWithContentsOfURL:options:error: and NSDataReadingMappedIfSafe or NSDataReadingMappedAlways instead.
------编辑--------

这是我正在使用的更新代码。它以iOS 9.1为目标编译和运行

let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "json")
let jsonData = NSData(contentsOfFile:path!)
let json = JSON(data: jsonData!)
Swift 3/4版本:

let path = Bundle.main.path(forResource: "JSON", ofType: "json")!
let jsonString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
let json = JSON(parseJSON: jsonString!)

现在我有了,它仍然打印“零”。这并不能回答问题。问题是如何从文件加载JSON。我发现这个答案非常有用。现在建议使用Bundle.main.url而不是Bundle.main.path。