【问题标题】:How to convert from String to Int in Json.Decoder如何在 Json.Decoder 中将 String 转换为 Int
【发布时间】:2015-09-07 18:06:40
【问题描述】:

这是我的解码器:

decodeData : Json.Decoder (Id, String)
decodeData =
  Json.at ["data", "0"]
    <| Json.object2 (,)
      ("id" := Json.int)
      ("label" := Json.string)

id 在逻辑上应该是Int,但是我的后端将它发送为String(例如,我们得到"1" 而不是1)。

如何将解码后的值转换为Int

【问题讨论】:

    标签: json elm


    【解决方案1】:

    ...并回答自己:) 我在这个 Flickr 示例中找到了解决方案

    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)
    

    【讨论】:

      【解决方案2】:

      在 Elm-0.18 中

      使用parseInt解码器(source):

      decodeString parseInt """ "123" """
      

      这里是tutorial 关于自定义解码器,比如日期。重复使用fromResult 方法。

      【讨论】:

        【解决方案3】:

        经过验证的答案已过时。这是 Elm 0.19 的答案:

        dataDecoder : Decoder Data
        dataDecoder =
            Decode.map2 Data
                (Decode.field "id" (Decode.string |> Decode.andThen stringToIntDecoder))
                (Decode.field "label" Decode.string)
        
        
        stringToIntDecoder : String -> Decoder Int
        stringToIntDecoder year =
            case String.toInt year of
                Just value ->
                    Decode.succeed value
        
                Nothing ->
                    Decode.fail "Invalid integer"
        

        还有一个executable example

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-04
          • 2017-03-19
          • 2011-07-31
          • 2022-01-02
          • 1970-01-01
          相关资源
          最近更新 更多