忽略 swift Codable 中的以下属性?

Nin*_*per 1 json swift urlsession codable

我有这个帐户结构。当我发送“POST”端点并使用它们将成功解码返回给 swift 对象时,我想忽略以下属性环境和 Id 编码到 JSON 对象

更新我有这个错误属性类型'[环境]'与其包装类型'SkipEncode'的'wrappedValue'属性不匹配

struct Account: Codable {
    let accountID, displayName, managedByID, id: String
    let environments: [Environment]
    let contacts: [Contact]

    enum CodingKeys: String, CodingKey {
        case accountID
        case displayName
        case managedID
        case id
        case environments
        case contacts
    }
}
Run Code Online (Sandbox Code Playgroud)

New*_*Dev 7

另一种方法,如果您不想手动实现encode(to:)并放弃Codable自动合成的好处,您可以创建一个属性包装器作为标记要跳过的属性的一种方式:

@propertyWrapper
struct SkipEncode<T> {
   var wrappedValue: T
}

extension SkipEncode: Decodable where T: Decodable {
   init(from decoder: Decoder) throws {
      let container = try decoder.singleValueContainer()
      self.wrappedValue = try container.decode(T.self)
   }
}

extension SkipEncode: Encodable {
   func encode(to encoder: Encoder) throws {
      // nothing to do here
   }
}

extension KeyedEncodingContainer {
   mutating func encode<T>(_ value: SkipEncode<T>, forKey key: K) throws {
      // overload, but do nothing
   }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以@SkipEncode像这样使用:

struct Account: Codable {
    let accountID, displayName, managedByID: String
    let contacts: [Contact]
    
    @SkipEncode
    let id: String

    @SkipEncode 
    let environments: [Environment]
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*Hua 5

如果你想忽略,例如environments在编码时,你可以定义自己的编码实现:

struct Account: Codable {
    let accountID, displayName, managedByID, id: String
    let environments: [Environment]
    let contacts: [Contact]

    enum CodingKeys: String, CodingKey {
        case accountID, displayName, managedByID, id, environments, contacts
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(accountID, forKey: .accountID)
        try container.encode(displayName, forKey: .displayName)
        // ... just don't include the environments here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我只想删除编码键。你不需要它们。 (4认同)