【发布时间】:2021-10-02 19:40:43
【问题描述】:
是否可以在调用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: "Could not decode property ",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").", 基础错误: nil)))))
o7 尚未匹配类型要求,但o7.configure() 完成了所需的步骤,是否可以在调用configure 后“询问”检查类型?
这是 JSON:{"name": "xxx"}
这是类型:
final class Organization: Content {
var name: String?
var events: [String: Event]
}
如您所见,我需要初始化 events 以避免 typeMismatch 错误。我是用configure 方法做的。
【问题讨论】:
-
再次,如果您显示它的迁移、模型和 JSON 字符串,帮助会容易得多
-
嗨,我在问题中添加了 JSON :)
-
所以事件是可选的。顺便说一句,显示您的模型迁移
-
不不,事件不是可选的,这是诀窍,但它不是在JSON中发送的,所以我必须在
var events: [String: Event]之间添加它 -
所以创建另一个模型来解码它。