在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">>我的问题是它是如何工作的?它是预期行为还是随机的不可靠特性?
发布于 2017-12-30 06:52:49
这是意料之中的,文档不正确。
https://stackoverflow.com/questions/48029005
复制相似问题