问题描述
我有一个名为 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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!