首页 > 解决方案 > 将 JSON 响应保存为 JSON 文件

问题描述

我想将我的 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()
}

//我在我的视图控制器中调用它

    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 中,因此也可以接受更新的方法。

标签: jsonswift

解决方案


保存:-

 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]


推荐阅读