我有struct
符合Codable
-protocol的。我实现了一个自定义encode
-func 以便我可以控制编码过程。但我并不是在所有情况下都需要这种自定义编码,有时我想依赖 Foundation 本身的编码。是否可以告诉JSONEncoder
我想要什么样的编码(比如创建编码策略)?
这是我的代码的简化版本:
struct User: Codable {
var name: String
var age: Int
var phone: PhoneNumber
struct PhoneNumber: Codable {
var countryCode: Int
var number: Int
enum CodingKeys: CodingKey {
case countryCode, number
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// I would like to have control over the next line, so that either
// the countryCode is encoded or not, like:
// if conditon {
try container.encode(self.countryCode, forKey: .countryCode)
// }
try container.encode(self.number, forKey: .number)
}
}
}
let user = User(name: "John", age: 12, phone: User.PhoneNumber(countryCode: 49, number: 1234567))
let jsonData = try! JSONEncoder().encode(user)
print(String(data: jsonData, encoding: .utf8)!)
更新
回答其中一个评论:这并不是真正包含或排除一个属性,而是更多地关于更改属性的类型或内容:
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// if conditon {
try container.encode("\(self.countryCode)".data(using: .utf8), forKey: .countryCode)
// }
try container.encode(self.number, forKey: .number)
}