我正在尝试对Codable
对象做一些自定义。我的JSON对象使用多种类型的令牌,因此我想使其安全。为此,我创建了以下Codable类:
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))
答案 0 :(得分:0)
我最接近干净的东西是:
首先,扩展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
对象上执行此操作的解决方案,那就太好了。我有很多具有许多属性的对象,而这些属性必须手动实现其编码/解码方法。