gpt4 book ai didi

json - 将 JSON 响应保存为 JSON 文件

转载 作者:行者123 更新时间:2023-11-28 07:23:02 24 4
gpt4 key购买 nike

我想将我的 JSON 响应保存到文档或任何其他目录中的 JSON 文件。

之前我试图将响应保存在 coreData 中,但这是一项繁重且缓慢的任务。

//API管理函数

func loadEmployees(urlString: String, completion: @escaping ((Any?,Error?) -> ())){

guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url)

request.httpMethod = RequestMethod.get.rawValue

let session = URLSession.shared
let sessionTask = session.dataTask(with: request) { (data, response, error) in

if error == nil {
let result = try? JSONDecoder().decode([EmployeeDetails].self, from: data!)
completion(result, nil)
}
else {
completion(nil, ServiceError.customError("Please check your internet connection"))
}
}
sessionTask.resume()
}

//我在我的 View Controller 中调用它

    NetworkManager.sharedInstance.loadEmployees(urlString: EMPLOYEEBASEURL, completion: { (data, responseError) in

if let error = responseError {
self.showToast(controller: self, message: error.localizedDescription, seconds: 1.6)
}else{
if data != nil {
DispatchQueue.global().async {
self.employeeListArray = data as! [EmployeeDetails]
self.filteredEmployeeArray = self.employeeListArray

DispatchQueue.main.async {
self.loader.isHidden = true
self.employeeTableView.reloadData()
}
}
}
}
})

//我的模型

struct EmployeeDetails: Decodable {
let id: String?
let name: String?
let salary: String?
let age: String?
let profileImage: String?

enum CodingKeys: String, CodingKey {
case id = "id"
case name = "employee_name"
case salary = "employee_salary"
case age = "employee_age"
case profileImage = "profile_image"
}
}

现在我不想直接解析它,而是想将响应保存在一个 json 文件中并从该文件中解析。

如果需要,我可以安装任何 pod,我的项目是 Swift 5.0,所以更新的方法也可以接受。

最佳答案

要保存:-

 func saveJsonFile(_ name:String, data:Data) {
// Get the url of File in document directory
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent(name + ".json")

// Transform array into data and save it into file
do {
//let data = try JSONSerialization.data(withJSONObject: list, options: [])
try data.write(to: fileUrl, options: .completeFileProtection)
} catch {
print(error)
}
}

检索:-

func retrieveFromJsonFile(_ name:String) -> [JSONObject]? {
// Get the url of File in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil}
let fileUrl = documentsDirectoryUrl.appendingPathComponent(name + ".json")

// Check for file in file manager.
guard (FileManager.default.fileExists(atPath: fileUrl.path))else {return nil}

// Read data from .json file and transform data into an array
do {
let data = try Data(contentsOf: fileUrl, options: [])
guard let list = try JSONSerialization.jsonObject(with: data, options: []) as? [JSONObject] else { return nil}
//print(list)
return list
} catch {
print(error)
return nil
}
}

删除json文件:-

func removeFile(with name: String){
// Path for the file.
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return}
let fileUrl = documentsDirectoryUrl.appendingPathComponent(name + ".json")

if (FileManager.default.fileExists(atPath: fileUrl.absoluteString)){
do{
try FileManager.default.removeItem(at: fileUrl)
}catch{
print(error.localizedDescription)
}
}
}

其中 JSONObject:- [String: Any]

关于json - 将 JSON 响应保存为 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com