JSON.mapping宏如何与union类型的参数一起使用?

问题描述 投票:4回答:1

JSON.mapping documentation明确指出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

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

Response.from_json json1

将输出:

#<Response:0x10d20ce20
  @ok=true,
  @result=
  [#<Update:0x10d20cc60 @id=1, @type="update">,
   #<Update:0x10d20cbe0 @id=2, @type="update">]>

Response.from_json json2

将输出:

#<Response:0x10d20c180
  @ok=true,
  @result=#<Message:0x10e241f80 @type="message">>

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

crystal-lang
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.