我正在下载一个JSON文件,我已将其检查为带有“ https://jsonlint.com”的有效JSON到文档目录。然后,我打开文件并再次检查它,它显示为无效JSON。那怎么可能?这是代码:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent("analysis."+pathExtension)
return (documentsURL, [.removePreviousFile])
}
Alamofire.download("http://www...../analysis.json", to: destination).response { response in
if response.destinationURL != nil {
print(response.destinationURL!)
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let path = documentsDirectory + "/analysis.json"
if JSONSerialization.isValidJSONObject(path) {
print("Valid Json")
} else {
print("InValid Json") ///// I am getting here "INValid Json" - how is that possible????
}
}
}
答案 0 :(得分:2)
因为path
是一个字符串,指示文件在系统中的位置,类似于file://path/to/analysis.json
。那显然是无效的JSON。
您要检查的是该文件的内容是有效的JSON。试试这个:
Alamofire.download("http://www...../analysis.json", to: destination).response { response in
guard detinationURL = response.destinationURL else { return }
guard data = Data(contentsOf: destinationURL) else { return }
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
} catch {
print("InValid Json")
}
}
附带说明:为什么不使用Decodable
?