【问题标题】:How can I read JSON file from disk and store to array in Swift如何从磁盘读取 JSON 文件并在 Swift 中存储到数组
【发布时间】:2014-06-07 02:10:11
【问题描述】:

我想以 swift 文件的形式从磁盘读取文件。它可以是相对路径或直接路径,没关系。我该怎么做?

我一直在玩这样的东西

let classesData = NSData .dataWithContentsOfMappedFile("path/to/classes.json");

它找到了文件(即不返回 nil),但我不知道如何操作并转换为 JSON,返回的数据。它不是字符串格式,并且 String() 无法处理它。

【问题讨论】:

    标签: json swift


    【解决方案1】:

    您需要拨打NSJsonSerialization.JSONObjectWithData:

    var error : NSError?
    var json = NSJSONSerialization.JSONObjectWithData(classesData, options: nil, error: &error)
    

    【讨论】:

      【解决方案2】:

      您可以使用良好的旧 Cocoa 类。

      let p1  =   "/path/to/any.json"
      let d1  =   NSData(contentsOfFile: p1)
      let a1 : AnyObject! =   NSJSONSerialization.JSONObjectWithData(d1, options: NSJSONReadingOptions(0), error: nil)
      
      println(a1)
      

      【讨论】:

        猜你喜欢
        • 2022-10-30
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        • 2011-09-07
        相关资源
        最近更新 更多