4
JSON.mapping
documentationtype
の値は単一のタイプである必要があります。しかし、実際の労働組合の種類でも動作します:JSON.mappingマクロはどのように共用体型の引数で動作しますか?
Response.from_json
を呼び出す
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
は、結果出力が期待されます。
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">>
私の質問は、それが動作しない方法ですか?予想される動作か、ランダムで信頼できない機能ですか?
その場合、マクロは通過するjsonに適用するタイプをどのように選択しますか?次のプレーを考慮してください - https://play.crystal-lang.org/#/r/3b84 'Message'と' Nessage'型は同じですが、どのような順序でクラス宣言や型共用体で指定しても、マッパーは常に 'Message'を選択します。 – vtambourine
アルファベット順です。 – RX14