The JSON.mapping
documentation explicitly states that the property value type
must be of the same type. However, in practice the types of trade unions also operate:
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
A call Response.from_json
in a JSON string displays the expected result.
Response.from_json json1
will output:
#<Response:0x10d20ce20
@ok=true,
@result=
[#<Update:0x10d20cc60 @id=1, @type="update">,
#<Update:0x10d20cbe0 @id=2, @type="update">]>
and
Response.from_json json2
will output:
@ok=true,
@result=
My question is, how does it work? Is behavior or an occasional unreliable function expected?
source
share