Hope you are doing good. I have a problem that I am collecting record from an api and store it to a structure. Problem is that if a single value of the record is missing, the decoding process throws error. i.e whole record is gone. I'll be very grateful to hear you on this. Thanks.
Below is my code:
HttpRequestHelper().GET(url: urlString, params: \["":""\], httpHeader: .application_json) { success, data in
if success {
do {
let model = try JSONDecoder().decode(EmployeesModel.self, from: data!)
completion(success, model, nil)
} catch let error {
completion(false, nil, error.localizedDescription)
}
} else {
completion(false, nil, "Error: Employees Get Requests failed")
}
}
and the EmployeeModel is:
typealias EmployeesModel = [EmployeeModel]
struct EmployeeModel: Codable {
let age: String
let id: String
let name: String
let salary: String
enum CodingKeys: String, CodingKey {
case id
case name = "name"
case salary = "salary"
case age = "age"
}
}
CodePudding user response:
Try use optional. if you use same property naming don't have to use CodingKeys.
struct EmployeeModel: Codable {
let age: String?
let id: String?
let name: String?
let salary: String?
}