使用 Swift 3 读取 JSON 文件 [英] Read JSON file with Swift 3

查看:17
本文介绍了使用 Swift 3 读取 JSON 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON file called points.json, and a read function like:

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

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

It does not work, any help?

推荐答案

你的问题是你强制解包值,如果出现错误你不知道它来自哪里.

Your problem here is that you force unwrap the values and in case of an error you can't know where it comes from.

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

Instead, you should handle errors and safely unwrap your optionals.

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

And as @vadian rightly notes in his comment, you should use 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 和其他),但尽量不要使用 ! 强制解包,而是始终安全解包.

When coding in Swift, usually, ! is a code smell. Of course there's exceptions (IBOutlets and others) but try to not use force unwrapping with ! yourself and always unwrap safely instead.

这篇关于使用 Swift 3 读取 JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆