ios - Swift 3.0 - 从 XCode 包中读取 .JSON 文件

标签 ios json swift3 xcode8 bundle

我在我的项目中保留了这些 .plist 和 .json 文件。我可以从 Xcode 读取 .plist 文件。虽然无法在 Swift 3.0 上读取 .json 文件。我使用下面的代码片段来获取它。但不能那样做。是否可以从 .json 文件中获取数据? 请分享您的建议。

可以获取 PLIST 文件

let plistFile = Bundle.main.path(forResource: "content", ofType: "plist")
let dictPlist = NSDictionary(contentsOfFile: plistFile!)
print(dictPlist ?? "")

无法获取 JSON 文件

    if let filepath = Bundle.main.path(forResource: "fruits", ofType: "json") {
        do {
            let contents = try String(contentsOfFile: filepath)
            print(contents)
        } catch {
            print("Fetched")
        }
    } else {
        print("not found")
    }

最佳答案

Swift 4 解决方案

如果正确找到文件路径,则可能是文件编码有问题。您应该明确提供 json 文件的实际编码。

要检查文件的编码,请在 XCode 中打开文件并查看右侧栏中的文件检查器:

Encoding of the file

if let filePath = Bundle.main.path(forResource: "data", ofType: "json"),
   let data = NSData(contentsOfFile: filePath) {
  do {

    // here you have your json parsed as string:
    let jsonString = try? String(contentsOfFile: filePath, encoding: String.Encoding.utf8)

    // but it is better to use the type data instead:
    let jsonData = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)
  }
  catch {
    //Handle error
  }
}

关于ios - Swift 3.0 - 从 XCode 包中读取 .JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892194/

相关文章:

javascript - 为什么我的 JSON 数据作为数据属性从 erb 传递到 Javascript 时会丢失?

python - 响应类型的对象不是 JSON 可序列化的

javascript - 我们需要更深入 - 在 Vanilla Javascript 中使用 foreach 循环深度访问 JSON 和数组

swift - 带参数的 GET 请求

ios - 在 iOS 上以小型大写字母排版字体

ios - Xcode 5.1 显示错误你的应用程序与 iPhone 5 不兼容

ios - "Objective-C Generated Interface Header Name"错误

android - 用于测试 Android 和 iOS 的 Calabash 目录结构

iOS VoIP 推送通知在 1-2 秒后自动停止

ios - 获取自定义单元格中标签的高度以用于主视图 Controller 中的 heightForRowAt