手动解码 Codable class 的非 Codable 属性

Decoding manually a non Codable property of a Codable class

ClassA 符合 Cadable 并且有一堆属性。其中之一是不符合 Codable 的已经存在的非常复杂的 ClassB 的 属性。我可以手动解码 Codable class 的非 Codable 属性 吗?

struct ClassA: Codable {

   let title: String?
   let subtitle: String?
   let property: ClassB?

    enum CodingKeys: String, CodingKey {
      case title
      case subtitle
      case property
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        title = try container.decode(String.self, forKey: .title)
        subtitle = try container.decode(String.self, forKey: .subtitle)
        let JSONString = ?
        property = ClassB.initWith(JSONString: JSONString)
  }

class ClassB: NSObject {

    // Already existing very complex ClassB implemenatation...
}

我收到错误:

Type 'ClassA' does not conform to protocol 'Encodable'

试试这个

struct ClassA: Codable {

   let title: String?
   let subtitle: String?
   let property: ClassB?

    enum CodingKeys: String, CodingKey {
      case title
      case subtitle
      case property
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        title = try container.decode(String.self, forKey: .title)
        subtitle = try container.decode(String.self, forKey: .subtitle)
        let JSONString = ?
        property = ClassB.initWith(JSONString: JSONString)
  }

class ClassB: Codable {

    // Already existing very complex ClassB implemenatation...
}

是的,你可以。

错误是您在 ClassA 中缺少 func encode(to encoder: Encoder) throwsCodable = Encodable & Decodable,所以它也在尝试找到一种编码 ClassA 的方法。 ClassB 不可编码,因此无法自动执行,而且您也没有告诉它如何手动执行。

如果您不需要编码 ClassA 个实例,只需将其设为 Decodable。否则实现缺少的 encode func.

或者只是投入工作并使 ClassB 也可编码。您可以使用扩展名在事后添加它。如果您也不想这样做,我使用的解决方法是在 ClassA 内声明一个小型私有可编码结构,例如 struct ClassBInfo: Codable。使用它来获取您需要的信息,然后读取其属性以初始化 ClassB.