Swift's Encodable/Decodable protocols, released with Swift 4, make JSON (de)serialization quite pleasant. However, I have not yet found a way to have fine-grained control over which properties should be encoded and which should get decoded.

I have noticed that excluding the property from the accompanying CodingKeys enum excludes the property from the process altogether, but is there a way to have more fine-grained control?

推荐答案

要编码/解码的密钥列表由名为CodingKeys的类型控制(请注意末尾的s).编译器可以为您综合这一点,但始终可以覆盖它.

Let's say you want to exclude the property nickname from both encoding and decoding:

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相关问答推荐

从先前的REST调用创建动态JSON主体

在PowerShell中,如何获取数据对所在的JSON对象的名称

如何创建生成两个不同对象的JSON数组的SQL查询?

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

使用 jolt 变换压平具有公共列 JSON 的复杂嵌套

如何将属性拆分为嵌套的JSON内容?

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

修改 boost::json::object 中的值

Powershell中等效的JSONPath通配符以 Select 对象中的所有数组

jq搜索特定字符串并输出对应的父值

如何将 XML 转换为 PsCustomObject 以允许最终导出为 JSON?

在 rust 中从 API 反序列化 serde_json

boost::json::value 的大括号初始化将其从对象转换为数组

如何使用 Serde 使用顶级数组反序列化 JSON?

如何使用 CORS 实现 JavaScript Google Places API 请求

在 Http Header 中使用 Json 字符串

如何在 Django JSONField 数据上聚合(最小/最大等)?

使用 application/json 优于 text/plain 的优势?

JSON 格式的 Amazon S3 响应?

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题