This question has been asked quite a few times over the years, but it has changed again in Swift 5, particularly in the last two betas.
Reading a JSON file seems to be quite simple:
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
}
But writing is incredibly difficult, and all of the previous methods found on this site have failed in Swift 5 on Xcode 11 betas 5 and 6.
How can I write data to a JSON file in Swift 5?
I tried these approaches:
- How to save an array as a json file in Swift?
- Writing JSON file programmatically swift
- read/write local json file swift 4
There weren't any errors except for deprecation warnings, and when I fixed those, it simply didn't work.