Ios 在Swift中使用可编码协议解码时如何识别?

Ios 在Swift中使用可编码协议解码时如何识别?,ios,swift,codable,Ios,Swift,Codable,我使用的是斯威夫特的编码协议。我已经分享了代码 我希望Employee类中的变量boss根据Person类中的personType字符串获取类型。我想使用personType作为鉴别器。根据personType值,每次来自服务器的响应都会不同 在Employee类中,我用Person类型声明了boss变量。如果Person类中的personType字符串为“Employee”,我希望它为类型Employee解码,如果personType字符串为“Boss”,则为类型Boss解码。如果它是空的,我

我使用的是斯威夫特的编码协议。我已经分享了代码

我希望Employee类中的变量boss根据Person类中的personType字符串获取类型。我想使用personType作为鉴别器。根据personType值,每次来自服务器的响应都会不同

在Employee类中,我用Person类型声明了boss变量。如果Person类中的personType字符串为“Employee”,我希望它为类型Employee解码,如果personType字符串为“Boss”,则为类型Boss解码。如果它是空的,我只是希望它为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)
    }
}
例如,在下面的响应中,在boss部分,personType设置为“boss”。所以它应该被解码为Boss类型。如果是“Employee”,则应自动解码为Employee,如果为null,则应解码为“Person”

{ 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 }

需要根据您发布的当前回复更改型号

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)")
    }
您可以在链接下载相同的工作演示

我会在
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
    }

区别对待你能告诉我你的服务器响应是什么吗?总的来说,如果你知道你想要什么类型的话,应该使用溺爱decode@Lu_我已经编辑并添加了服务器响应示例,使其更加清晰。谢谢