在 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
将输出:
#<0x10d20ce20>
@ok=true,
@result=
[#<0x10d20cc60>,0x10d20cc60>
#<0x10d20cbe0>]>0x10d20cbe0>
和
Response.from_json json2
将输出:
#<0x10d20c180>
@ok=true,
@result=#<0x10e241f80>>0x10e241f80>
我的问题是它是如何工作的?它是预期的行为还是随机不可靠的特征?
0x10d20c180>0x10d20ce20>