swift - 在 Swift 中创建自定义 CodingKey 对象

标签 swift codable

我正在尝试用我的 Codable 对象做一些自定义的事情。我的 JSON 对象使用多种类型的标记,因此我想让它们类型安全。为此,我创建了以下可编码类:

class Token: Codable {
    let value: String

    init(_ value: String = "") {
        self.value = value
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        value = try container.decode(String.self)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()

        try container.encode(value)
    }
}

extension Token: Equatable { }
extension Token: Hashable { }

class UserToken: Token { }
class ProductToken: Token { }
// etc...

struct User: Codable {
    let token: UserToken
    let friends: [UserToken : User]
    // ...
}

JSON 对象:

// User
{
    "token":"12345",
    ...
}

这非常有效,除了这些标记用作字典中的键的情况,如下所示:

// User
{
    "token":"12345",
    "friends":{
        "56789":{ // User
            "token":"56789",
            ...
        },
        "09876":{ // User
            "token":"09876",
            ...
        }
     }
}

为了使其正常工作,我更新了我的 Token 类以符合 CodingKey (似乎是正确的做法):

class Token: Codable, CodingKey {
    var stringValue: String {
        return value
    }

    var intValue: Int? {
        return Int(value)
    }

    required init?(stringValue: String) {
        value = stringValue
    }

    required init?(intValue: Int) {
        value = "\(intValue)"
    }

    // Plus above implementation
}

但这似乎无法正常工作,失败并出现以下错误。看起来 JSONDecoder 认为它应该解码数组而不是字典...这是 Codable 中的错误吗?

typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

最佳答案

我能得到的最接近干净的东西如下:

首先,扩展KeyedDecodingContainer(Token符合CodingKey):

extension KeyedDecodingContainer {

    func decodeTokenContainer<TokenKey, Value>(keyedBy tokenKeyType: TokenKey.Type,
                                               valueType: Value.Type,
                                               forKey key: KeyedDecodingContainer<K>.Key) throws -> [TokenKey : Value] where TokenKey: Token, Value: Decodable {
        let tempDict = try nestedContainer(keyedBy: tokenKeyType, forKey: key)

        var tokenDictionary = [TokenKey : Value]()
        for key in tempDict.allKeys {
            let value = try tempDict.decodeIfPresent(Value.self, forKey: key)
            tokenDictionary[key] = value
        }
        return tokenDictionary
    }
}

然后,您需要重写包含类的解码/编码方法:

struct User {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        ...

        friends = container.decodeTokenContainer(keyedBy: UserToken.self, 
                                                 valueType: User.self, 
                                                 forKey: .friends)
    }
}

如果有人有一个解决方案,我不需要在 User 对象上执行此操作,那就太好了。我有很多具有很多属性的对象,我必须手动实现它们的编码/解码方法。

关于swift - 在 Swift 中创建自定义 CodingKey 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56449505/

相关文章:

swift - 如何在 Swift 中捕获 NSKeyedUnarchiver "NSInvalidUnarchiveOperationException"?

json - 在 Swift 4 中解码 JSON

ios - 具有原始值的枚举,可编码

ios - 台风参数注入(inject)与初始化器崩溃应用程序

ios - 如何创建一组自定义对象 (Swift)?

ios - swift - 在 UITableVIew 中将多选设置为 true 时如何设置选择颜色

swift - 可解码,不解码具有无效值的可选枚举

ios - 在 iOS 12 中获取数据

ios - 如何从 Apple Watch 触发与后端的通信?

swift - 结果类型 通用参数 'T' 无法快速推断 5