使用Swift 3读取JSON文件

Xie*_*Xie 35 json swift3

我有一个名为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)
}
Run Code Online (Sandbox Code Playgroud)

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

aya*_*aio 98

这里的问题是你强制打开值,如果出现错误,你就无法知道它的来源.

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

正如@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)
    }
}
Run Code Online (Sandbox Code Playgroud)

在Swift编码时,通常!是代码气味.当然有例外(IBOutlets和其他人),但试着不要用!自己的力量展开,而是总是安全地解开.

  • `通常,!是一种代码气味...尽量不要用力展开!自己,总是安全地解开.+ 1 (5认同)
  • 是的,这是捕获JSONSerialization错误的`catch`.您的JSON文件可能无效.请参阅:始终处理错误.:) (2认同)

Ima*_*tit 5

下面的 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)")
    }
}
Run Code Online (Sandbox Code Playgroud)