json - 忽略 swift Codable 中的以下属性?
问题描述
我有这个 Account 结构。当我发送“POST”端点并使用它们将成功解码返回给 swift 对象时,我想忽略以下属性环境和编码到 JSON 对象的 Id
更新我有这个错误属性类型'[Environment]'与它的包装器类型'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
}
}
解决方案
另一种方法,如果您不想手动实现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
}
}
然后你可以@SkipEncode
像这样使用:
struct Account: Codable {
let accountID, displayName, managedByID: String
let contacts: [Contact]
@SkipEncode
let id: String
@SkipEncode
let environments: [Environment]
}
推荐阅读
- symfony - 如何使用 bootstrap 和 twig 自定义 symfony 表单错误?
- angular - 如何表示表格组件中的元素
- python - 将列表作为嵌套列表,在单独的列表中具有连续元素
- excel - 使用 HSL 函数时如何修复“未定义子或函数”
- sql-server - 如何在 SQL Server 中对具有 ABC、ABC123,123 等数据的 Varchar 字段进行排序
- graphql - Apollo GraphQL 服务器中的突变调用有什么问题?
- amazon-web-services - 使用 github 和 AWS lambda 的最佳实践?
- c# - 无法将用户上下文 ID 发送到 Azure Application Insights
- python - RecursionError:我正在寻找一种减少循环次数的方法
- c# - C# 读取 Xml - LinQ