JSON.mapping 宏如何处理联合类型的参数?

vta*_*ine 5 crystal-lang

JSON.mapping 文档中明确指出属性的值type应该是单一类型。然而,实际上联合类型也有效:

json1 = %q({"ok": true, "result": [{"type": "update", "id": 1}, {"type": "update", "id": 2}]})
json2 = %q({"ok": true, "result": {"type": "message"}})

class Response
  JSON.mapping({
    ok: Bool,
    result: Message | Array(Update)
  })
end

class Update
  JSON.mapping({
    type: String,
    id: Int32
  })
end

class Message
  JSON.mapping({
    type: String
  })
end
Run Code Online (Sandbox Code Playgroud)

调用Response.from_json这两个 JSON 字符串将输出预期结果。

Response.from_json json1
Run Code Online (Sandbox Code Playgroud)

将输出:

#<Response:0x10d20ce20
  @ok=true,
  @result=
  [#<Update:0x10d20cc60 @id=1, @type="update">,
   #<Update:0x10d20cbe0 @id=2, @type="update">]>
Run Code Online (Sandbox Code Playgroud)

Response.from_json json2
Run Code Online (Sandbox Code Playgroud)

将输出:

#<Response:0x10d20c180
  @ok=true,
  @result=#<Message:0x10e241f80 @type="message">>
Run Code Online (Sandbox Code Playgroud)

我的问题是它是如何运作的?是预期的行为还是随机的不可靠特征?

RX1*_*X14 1

这是预期的,文档不正确。