如何在Json.Decoder中将String转换为Int
问题描述:
这是我的解码器:
decodeData : Json.Decoder (Id, String)
decodeData =
Json.at ["data", "0"]
<| Json.object2 (,)
("id" := Json.int)
("label" := Json.string)
id
在逻辑上应为Int
,但是我的后端将其作为String
发送(例如,我们得到了"1"
而不是1
).
The id
should logically be Int
however my backend sends it as String
(e.g. we get "1"
instead of 1
).
如何将解码后的值转换为Int
?
How can I cast the decoded value to Int
?
答
... and to answer myself :) I found the solution in this Flickr example
decodeData : Json.Decoder (Id, String)
decodeData =
let number =
Json.oneOf [ Json.int, Json.customDecoder Json.string String.toInt ]
in
Json.at ["data", "0"]
<| Json.object2 (,)
("id" := number)
("label" := Json.string)