使用 Swift 3 读取 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40438784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read JSON file with Swift 3
提问by Xie
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?
它不起作用,有什么帮助吗?
回答by Eric Aya
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 中编码时,通常!是代码异味。当然,也有例外(IBOutlets 和其他),但尽量不要对!自己使用强制解包,而是始终安全地解包。
回答by Imanou Petit
The Swift 5 / iOS 12.3 code below shows a possible rewrite of your method that avoids force unwrap on optional values and handles gently potential errors:
下面的 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)")
}
}

