swift - 仅在特定情况下使用编码功能
问题描述
我有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)
}
解决方案
推荐阅读
- c# - 显示两个日期时间选择器之间的数据,“条件表达式中的数据类型不匹配”
- db2 - 在 SQLCODE=-181, SQLSTATE=22007, SQLERRMC=0;*N, DRIVER=3.61.75 的 DB2 Sql 错误中面临问题
- android - 实时 admob 广告未在我的设备上显示
- c# - Wpf 样式未完全应用于 ContextMenu
- javascript - Javascript 在 PHP 标记后停止工作
- android - Android Studio:如何在启用 Orchestrator 的 Firebase 中运行测试?
- amazon-web-services - 将现有 AWS Lambda 和 API Gateway 导出到 Cloudformation 模板
- php - 对公共 API“不支持的媒体类型”的 PHP Curl 请求
- java - 如何下载从数据库中获取结果集的excel表
- c - Threads in C in Windows