在 Swift 中以正确的方式解码来自 URLSession 的原始数据
Decoding raw data from URLSession the right way in Swift
我 API 中大多数端点的响应是这样的 -
{
"status":"success",
"data":[
{
"id":"1",
"employee_name":"Tiger Nixon",
"employee_salary":"320800",
"employee_age":"61",
"profile_image":""
},
{
"id":"2",
"employee_name":"Garrett Winters",
"employee_salary":"170750",
"employee_age":"63",
"profile_image":""
}
]
}
这就是我的员工模型的样子
struct Employee: Codable {
let id, employeeName, employeeSalary, employeeAge: String
let profileImage: String?
enum CodingKeys: String, CodingKey {
case id
case employeeName = "employee_name"
case employeeSalary = "employee_salary"
case employeeAge = "employee_age"
case profileImage = "profile_image"
}
}
typealias Employees = [Employee]
我只想使用 JSONDecoder
提取 API 响应的数据部分并将其传递给我的完成处理程序
completionHandler(try? JSONDecoder().decode(Employees.self, from: data), response, nil)
我能够通过创建这样的结构 Employees 来绕过 -
struct Employees: Codable {
let status: String
let data: [Employee]
}
但这只是一种解决方法,我必须对几乎所有模型都这样做。那么有没有更好、更少冗余的方式从响应中提取数据呢?
如果我是你,我会做的只是创建一个基于模板的包装器并将其用于所有模型对象。
struct ModelWrapper<T: Codable>: Codable {
let status: String
let data: [T]
}
let decoder = JSONDecoder()
let wrapper = try decoder.decode(ModelWrapper<Employee>.self, from: json)
我 API 中大多数端点的响应是这样的 -
{
"status":"success",
"data":[
{
"id":"1",
"employee_name":"Tiger Nixon",
"employee_salary":"320800",
"employee_age":"61",
"profile_image":""
},
{
"id":"2",
"employee_name":"Garrett Winters",
"employee_salary":"170750",
"employee_age":"63",
"profile_image":""
}
]
}
这就是我的员工模型的样子
struct Employee: Codable {
let id, employeeName, employeeSalary, employeeAge: String
let profileImage: String?
enum CodingKeys: String, CodingKey {
case id
case employeeName = "employee_name"
case employeeSalary = "employee_salary"
case employeeAge = "employee_age"
case profileImage = "profile_image"
}
}
typealias Employees = [Employee]
我只想使用 JSONDecoder
提取 API 响应的数据部分并将其传递给我的完成处理程序
completionHandler(try? JSONDecoder().decode(Employees.self, from: data), response, nil)
我能够通过创建这样的结构 Employees 来绕过 -
struct Employees: Codable {
let status: String
let data: [Employee]
}
但这只是一种解决方法,我必须对几乎所有模型都这样做。那么有没有更好、更少冗余的方式从响应中提取数据呢?
如果我是你,我会做的只是创建一个基于模板的包装器并将其用于所有模型对象。
struct ModelWrapper<T: Codable>: Codable {
let status: String
let data: [T]
}
let decoder = JSONDecoder()
let wrapper = try decoder.decode(ModelWrapper<Employee>.self, from: json)