gpt4 book ai didi

json - 如何从 Swift Codable 中排除属性?

转载 作者:IT老高 更新时间:2023-10-28 12:44:09 50 4
gpt4 key购买 nike

Swift 的 Encodable/Decodable 协议(protocol)与 Swift 4 一起发布,使 JSON(反)序列化非常愉快。但是,我还没有找到一种方法来细粒度地控制哪些属性应该被编码,哪些应该被解码。

我注意到从随附的 CodingKeys 枚举中排除该属性会完全将该属性排除在进程之外,但是有没有办法进行更细粒度的控制?

最佳答案

要编码/解码的键列表由称为 CodingKeys 的类型控制(注意末尾的 s)。编译器可以为您合成它,但始终可以覆盖它。

假设您想从编码解码中排除属性nickname:

struct Person: Codable {
var firstName: String
var lastName: String
var nickname: String?

private enum CodingKeys: String, CodingKey {
case firstName, lastName
}
}

如果您希望它是非对称的(即编码但不解码,反之亦然),您必须提供自己的 encode(with encoder: )init(from decoder :):

struct Person: Codable {
var firstName: String
var lastName: String

// Since fullName is a computed property, it's excluded by default
var fullName: String {
return firstName + " " + lastName
}

private enum CodingKeys: String, CodingKey {
case firstName, lastName, fullName
}

// We don't want to decode `fullName` from the JSON
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
}

// But we want to store `fullName` in the JSON anyhow
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(firstName, forKey: .firstName)
try container.encode(lastName, forKey: .lastName)
try container.encode(fullName, forKey: .fullName)
}
}

关于json - 如何从 Swift Codable 中排除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655562/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com