如何从Swift 4的Codable中排除属性 [英] How to exclude properties from Swift 4's Codable

查看:641
本文介绍了如何从Swift 4的Codable中排除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swfit 4的新Encodable/Decodable协议使JSON(反)序列化变得非常令人愉快.但是,我还没有找到一种方法可以对应该编码的属性和应该解码的属性进行细粒度控制.

Swfit 4's new Encodable/Decodable protocols 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.

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

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).编译器可以为您合成该信息,但始终可以覆盖它.

The list of keys to encode/decode is controlled by a type called CodingKeys (note the s at the end). The compiler can synthesize this for you but can always override that.

假设您要在编码解码中都排除属性nickname:

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: )实现:


If you want it to be asymmetric (i.e. encode but not decode or vice versa), you have to provide your own implementations of encode(with encoder: ) and 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
        case lastName
        case fullName
    }

    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)
    }

    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)
    }
}

这篇关于如何从Swift 4的Codable中排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆