【问题标题】:How to retrieve data from file with SwiftyJSON如何使用 SwiftyJSON 从文件中检索数据
【发布时间】:2015-05-01 07:21:29
【问题描述】:

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

{ “DDD”:“3D Systems Corporation”,“MMM”:“3M 公司”,“WBAI”: “500.com Limited”、“WUBA”:“58.com Inc.”、“AHC”:“A.H. Belo Corporation”、“ATEN”:“A10 Networks, Inc.”、“AAC”:“AAC Holdings、 Inc.”、“AIR”:“AAR Corp.”}

我的文件名是 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。我的代码有什么问题?

任何建议将不胜感激。

【问题讨论】:

标签: json swift swifty-json


【解决方案1】:

你试过了吗

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

【讨论】:

  • 现在我有了,它仍然打印“nil”。
  • 这不能回答问题。问题是关于从文件中加载 JSON。
【解决方案2】:

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!)

【讨论】:

  • 现在推荐使用 Bundle.main.url 而不是 Bundle.main.path。
【解决方案3】:

我没有代表发表评论,但从 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!)

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2016-10-17
    • 2016-03-14
    相关资源
    最近更新 更多