我正在使用Swift的Codable协议。我已经分享了代码。
我希望Employee类中的变量boss根据Person类中的personType字符串获取类型。我想使用personType作为鉴别符。每次根据personType值,来自服务器的响应都会有所不同。
在Employee类中,我已经声明了Person类型的boss变量。如果Person类中的personType字符串是“ Employee”,我希望它为Employee类型解码;如果personType字符串是“ Boss”,我希望它为Boss类型解码。如果它为null,我只是希望它为Person类型解码。
任何帮助将不胜感激。
public class Person: Codable {
public let address: String
public let age: Int
public let name: String
public let uid: String
public let personType: String?
private enum CodingKeys: String, CodingKey {
case address
case age
case name
case uid
case personType
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
address = try container.decode(String.self, forKey: .address)
age = try container.decode(Int.self, forKey: .age)
name = try container.decode(String.self, forKey: .name)
uid = try container.decode(String.self, forKey: .uid)
personType = try container.decodeIfPresent(String.self, forKey: .personType)
}
}
public class Employee: Person {
public let department: String
public let dependents: [Person]?
public let salary: Int
public let workingDays: [Days]
public var boss: Person?
private enum CodingKeys: String, CodingKey {
case department
case dependents
case salary
case workingDays
case boss
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
department = try container.decode(String.self, forKey: .department)
dependents = try container.decode([Person].self, forKey: .dependents)
salary = try container.decode(Int.self, forKey: .salary)
workingDays = try container.decode([Days].self, forKey: .workingDays)
boss = try container.decode(Person.self, forKey: .boss)
try super.init(from: decoder)
}
}
public class Boss: Employee {
let promotedAt: Double
let assistant: Employee?
enum CodingKeys: String, CodingKey {
case promotedAt
case assistant
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
promotedAt = try container.decode(Double.self, forKey: .promotedAt)
assistant = try container.decodeIfPresent(Employee.self, forKey: .assistant)
try super.init(from: decoder)
}
}
例如,在以下响应中,在“老板”部分中,personType设置为“老板”。因此,应将其解码为Boss类型。如果是“雇员”,则应自动解码为“雇员”,如果为空,则应解码为“人”。
{ name: 'Shahid Khaliq',
age: 5147483645,
address: 'H # 531, S # 20',
uid: '123321',
salary: 20000,
department: 'Software Development',
workingDays: [ 'Monday', 'Tuesday', 'Friday' ],
boss:
{ personType: 'Boss',
assistant: null,
name: 'Zeeshan Ejaz',
age: 5147483645,
address: 'H # 531, S # 20',
uid: '123321',
birthday: '1994-02-13',
birthtime: '1994-02-13T14:01:54.000Z',
salary: 20000,
department: 'Software Development',
joiningDay: 'Saturday',
workingDays: [ 'Monday', 'Tuesday', 'Friday' ],
dependents: null,
hiredAt: 'Sun, 06 Nov 1994 08:49:37 GMT',
boss: null,
promotedAt: 1484719381 },
dependents: null,
hiredAt: 'Sun, 06 Nov 1994 08:49:37 GMT',
personType: null }
答案 0 :(得分:1)
需要根据您当前发布的回复更改模型
public class Employee: Person {
public let department: String
public let dependents: [Person]?
public let salary: Int
public let workingDays:[String] //[Days]
public var boss: Person?
private enum CodingKeys: String, CodingKey {
case department
case dependents
case salary
case workingDays
case boss
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
department = try container.decode(String.self, forKey: .department)
//dependents = try container.decode([Person].self, forKey: .dependents)
dependents = try container.decodeIfPresent([Person].self, forKey: .dependents)
salary = try container.decode(Int.self, forKey: .salary)
// workingDays = try container.decode([Days].self, forKey: .workingDays)
workingDays = try container.decode([String].self, forKey: .workingDays)
// boss = try container.decode(Person.self, forKey: .boss)
boss = try container.decodeIfPresent(Person.self, forKey: .boss)
try super.init(from: decoder)
}
}
此处在一些属性中添加了 decodeIfPresent ,因为根据当前响应它为空
在解码时,您可以使用其他东西,我使用了SwiftJSON使代码更具可读性,
// i have saved response in Response.JSON file so can change response as per need while testing below code.
let file = Bundle.main.path(forResource: "Response", ofType: "JSON")
let dataURL = URL(fileURLWithPath: file!)
let data = try! Data(contentsOf: dataURL)
let jsonData = try! JSON(data: data)
//here JSON is struct which is part of SwiftyJSON
print("jsondata \(jsonData)")
do {
let bossDict = jsonData["boss"]
let dataBoss : Data = try! bossDict.rawData()
let bossType = bossDict["personType"].string
if let type = bossType {
if type == "Boss"{
let bossObj = try! JSONDecoder().decode(Boss.self, from: dataBoss)
print("boss name \(String(describing: bossObj.name))")
bossObj.listPropertiesWithValues()
}else{
// type == "Employee"
let emplyeeObj = try! JSONDecoder().decode(Employee.self, from: dataBoss)
print("Employee name \(String(describing: emplyeeObj.name))")
emplyeeObj.listPropertiesWithValues()
}
}else{
//type = nil
}
}catch{
print("exception \(error)")
}
您可以通过链接下载相同版本的工作演示 DemoCodable
答案 1 :(得分:0)
我将在init(from decoder:)
类的Employee
的末尾添加一个switch语句
switch personType {
case "Boss":
boss = try container.decode(Boss.self, forKey: .boss)
case "Employee":
boss = try container.decode(Employee.self, forKey: .boss)
default:
boss = nil
}