I have a JSON file called points.json, and a read function like:
我有一个名为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)
}
It does not work, any help?
它不管用,有什么帮助吗?
1 个解决方案
#1
75
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.
相反,您应该处理错误并安全地打开您的选项。
And as @vadian rightly notes in his comment, you should use Bundle.main.url
.
正如@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)
}
}
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编码时,通常是!是一个代码味道。当然也有例外(iboutlet和其他),但是尽量不要使用强行展开!你自己,总是安全地打开包装。
#1
75
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.
相反,您应该处理错误并安全地打开您的选项。
And as @vadian rightly notes in his comment, you should use Bundle.main.url
.
正如@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)
}
}
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编码时,通常是!是一个代码味道。当然也有例外(iboutlet和其他),但是尽量不要使用强行展开!你自己,总是安全地打开包装。