在执行可编码解码类型检查之前执行代码?

问题描述

是否可以在调用 decode后执行类型检查之前执行代码

let o7 = try decoder.decode(Organization.self,from: o6)
o7.configure()
return o7.save(on: request.db).flatMap { page in
    return request.eventLoop.future("done")
}

它引发了一个错误

caught: typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath: [ModelCodingKey(stringValue: "events",intValue: nil)],debugDescription: "无法解码属性",underlyingError: Optional(Swift.DecodingError.keyNotFound(ModelCodingKey(stringValue: "events",intValue: nil),Swift.DecodingError.Context(codingPath: [],debugDescription: "No value associated with key ModelCodingKey(stringValue: "events) ",intValue: nil) ("events").",underlyingError: nil)))))

o7 还没有符合类型要求,但是 o7.configure() 做了需要的步骤,是否可以在调用 configure 后“询问”检查类型?


这是 JSON:{"name": "xxx"} 这是类型:

final class Organization:  Content {
    var name: String?
    var events: [String: Event]
}

如您所见,我需要初始化 events 以避免出现 typeMismatch 错误。我用 configure 方法来做。

解决方法

尝试添加 CodingKeys,这将从 json 可解码中排除“var events”。

final class Organization: Codable {
    var name: String?
    var events: [String: Event] = [:]
    
    private enum CodingKeys: String,CodingKey {
        case name
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...