作为解码操作的一部分,您能否将额外的状态数据传递给(可能是自定义的)JSONDecoder?

Can you pass additional state data through to a (possibly custom) JSONDecoder as part of the Decode operation?

我们有一个基于 Codable 协议的 tree-based 数据模型。树的根包含其直接 children,以及对层次结构中所有 children 的引用,如此处所示...

Root
 |
 |-->Children
 |   |
 |   |-->Item 1
 |   |-->Item 2
 |   |   |
 |   |   \-->Children
 |   |       |
 |   |       \-->Item 3
 |   |
 |   \-->Item 4
 |       |
 |       \-->Children
 |           |
 |           \-->Item 5
 |               |
 |               \-->Children
 |                   |
 |                   \-->Item 6
 |
 \-->AllChildren  <<-- Not Serialized!!
      |
      |-->Item 1
      |-->Item 2
      |-->Item 3
      |-->Item 4
      |-->Item 5
      \-->Item 6

现在 AllChildren 部分未序列化,因为它们只是对上面实际实例的引用。

为了完成上述工作,我们需要以编程方式填充 AllChildren,因为那些 children 正在被解码。但是,我们不确定如何将 Root object 传递到 children 的 init(from:Decoder) 调用中来处理这个问题,因为我们看不到任何方法来传递额外的状态数据进入解码链。似乎您唯一可用的信息是您无法控制的 Decoder

我们的 work-around 在 Rootinit(from:Decoder) 里面,一旦完成 decoding/initializing 它的所有 children,它就会 re-crawls 整个层次结构,吞噬了 children,但我真的很讨厌在 init(from:Decoder) 传递期间我必须 re-crawl 层次结构。

那么有没有办法将额外的状态信息传递到 Decode 进程中,最好是在 Decoder 上传递给 init(from:Decoder) 调用?

您可以将任意一组 key/value 对分配给解码器的 userInfo 并在 init 方法中读取它们。

请注意 userInfo 的键是 CodingUserInfoKey,但您可以使用 CodingUserInfoKey(rawValue: "key")!.

从字符串创建它们