如何在Json.Decoder中将String转换为Int [英] How to convert from String to Int in Json.Decoder
本文介绍了如何在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)
这篇关于如何在Json.Decoder中将String转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文