我有一个名为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)
}

没用了,有什么帮助吗?

推荐答案

这里的问题是,您强制展开值,如果出现错误,您无法知道它来自何处.

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

正如@vadian在他的 comments 中正确指出的,你应该使用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)
    }
}

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.

Json相关问答推荐

无法根据vega规范中的条件设置文本 colored颜色

PostgreSQL 12.17从JSON数组提取元素

Vega-Lite时钟(使用Vega-Lite中的计时器)

Jolt需要将缺少的值设置为空并保持相同的位置

在Zig中解析JSON失败

如果主对象中已存在属性,则不应在Jolt中引用次对象

419(未知状态)使用laravel处理PUT请求

如何在 Apps 脚本中循环遍历 JSON 响应

数据清理设计不良的 JSON 数据 - 需要有关最佳策略的建议

通过 xslt 将内部 json 转换为 xml 时遇到问题

JSON 字段的多个名称

将哈希表转换为 json 后,Powershell 缺少数组

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

在 C# 中解析 Json rest api 响应

Json.Net:用于自定义命名的 JsonSerializer-Attribute

Rails 中奇怪的 JSON Javascript 问题

从 JSON 创建 Hashtable

在 JSON.NET 中序列化派生类时的字段顺序

ASP.NET Web API JSON 输出中没有时间的日期