【问题标题】:Read JSON file with Swift 3使用 Swift 3 读取 JSON 文件
【发布时间】:2016-11-05 13:28:09
【问题描述】:

我有一个名为 points.json 的 JSON 文件和一个读取函数,例如:

private func readJson() {
    let file = Bundle.main.path(forResource: "points", ofType: "json")
    let data = try? Data(contentsOf: URL(fileURLWithPath: file!))
    let jsonData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
    print(jsonData)
}

它不起作用,有什么帮助吗?

【问题讨论】:

  • 什么不起作用?添加do - catch 块以获取错误信息。顺便说一句,BundleURL 相关的API来检索资源。

标签: json swift3


【解决方案1】:

您的问题是您强制解开值,如果出现错误,您无法知道它来自哪里。

相反,您应该处理错误并安全地打开您的选项。

正如@vadian 在他的评论中正确指出的那样,您应该使用Bundle.main.url

private func readJson() {
    do {
        if let file = Bundle.main.url(forResource: "points", withExtension: "json") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            if let object = json as? [String: Any] {
                // json is a dictionary
                print(object)
            } else if let object = json as? [Any] {
                // json is an array
                print(object)
            } else {
                print("JSON is invalid")
            }
        } else {
            print("no file")
        }
    } catch {
        print(error.localizedDescription)
    }
}

在 Swift 中编码时,! 通常是一种代码味道。当然也有例外(IBOutlets 和其他),但尽量不要自己使用! 强制解包,而是始终安全地解包。

【讨论】:

  • 谢谢!它打印“无法读取数据,因为它的格式不正确。”。
  • 所以我认为是json文件的问题
  • 是的,这是 catch 捕获来自 JSONSerialization 的错误。您的 JSON 文件可能无效。请参阅:始终处理错误。 :)
  • usually, ! is a code smell ... try to not use force unwrapping with ! yourself and always unwrap safely instead. +1
  • @ParamaDharmika 代码异味意味着代码有问题,而不是语言。你误解了我的话。我同意你的结论,实际上我们的想法是一样的……我说的是代码(写了什么),而不是用于编写它的语言。
【解决方案2】:

下面的 Swift 5 / iOS 12.3 代码显示了对您的方法的可能重写,以避免对可选值强制展开并温和地处理潜在错误:

import Foundation

func readJson() {
    // Get url for file
    guard let fileUrl = Bundle.main.url(forResource: "Data", withExtension: "json") else {
        print("File could not be located at the given url")
        return
    }

    do {
        // Get data from file
        let data = try Data(contentsOf: fileUrl)

        // Decode data to a Dictionary<String, Any> object
        guard let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            print("Could not cast JSON content as a Dictionary<String, Any>")
            return
        }

        // Print result
        print(dictionary)
    } catch {
        // Print error if something went wrong
        print("Error: \(error)")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多