在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">>
我的问题是它是如何运作的?它是预期的行为还是随机不可靠的特征?
答案 0 :(得分:0)
这是预期的,文档不正确。