多年来,这个问题已经问了好几次了,但是在Swift 5中,尤其是在最近的两个beta中,它再次发生了变化。
读取JSON文件似乎非常简单:
func readJSONFileData(_ fileName: String) -> Array<Dictionary<String, Any>> {
var resultArr: Array<Dictionary<String, Any>> = []
if let url = Bundle.main.url(forResource: "file", withExtension: "json") {
if let data = try? Data(contentsOf: url) {
print("Data raw: ", data)
if let json = try? (JSONSerialization.jsonObject(with: data, options: []) as! NSArray) {
print("JSON: ", json)
if let arr = json as? Array<Any> {
print("Array: ", arr)
resultArr = arr.map { $0 as! Dictionary<String, Any> }
}
}
}
}
return resultArr
}
但是编写起来非常困难,并且在该站点上找到的所有先前方法在Xcode 11 beta 5和6的Swift 5中都失败了。
如何在Swift 5中将数据写入JSON文件?
我尝试了以下方法:
除弃用警告外,没有任何错误,当我修复这些警告时,它根本不起作用。
让我们假设您有一些随机集合(数组或字典或其嵌套组合):
let dictionary: [String: Any] = ["bar": "qux", "baz": 42]
然后,您可以将其另存为JSON到“应用程序支持”目录中,如下所示:
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")
try JSONSerialization.data(withJSONObject: dictionary)
.write(to: fileURL)
} catch {
print(error)
}
要了解为什么我们现在使用“应用程序支持”目录而不是“文档”文件夹,请参阅iOS Storage Best Practices视频或参阅《文件系统编程指南》。但是,无论如何,我们都使用这些文件夹,而不是应用程序的“ bundle”文件夹,该文件夹是只读的。
并读取该JSON文件:
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("example.json")
let data = try Data(contentsOf: fileURL)
let dictionary = try JSONSerialization.jsonObject(with: data)
print(dictionary)
} catch {
print(error)
}
话虽这么说,我们通常更喜欢使用强类型的自定义类型,而不是使用随机字典,因为这会给程序员带来负担,以确保键名中没有拼写错误。无论如何,我们使这些自定义struct
或class
类型符合Codable
:
struct Foo: Codable {
let bar: String
let baz: Int
}
然后,我们将使用JSONEncoder
而不是旧的JSONSerialization
:
let foo = Foo(bar: "qux", baz: 42)
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")
try JSONEncoder().encode(foo)
.write(to: fileURL)
} catch {
print(error)
}
并读取该JSON文件:
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("example.json")
let data = try Data(contentsOf: fileURL)
let foo = try JSONDecoder().decode(Foo.self, from: data)
print(foo)
} catch {
print(error)
}
有关从自定义类型准备JSON的更多信息,请参见编码和解码自定义类型文章或使用JSON与自定义类型示例代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句