json - 如何在 Elm 中解码标记的联合类型?

标签 json elm decoder

如果我有某个标记的联合类型,例如 Shape在这里,我将如何在 Elm 中为它构建一个 JSON 解码器?

type alias Rectangle = { width : Int, height : Int }

type alias Circle = { radius: Int }

type Shape 
    = ShapeRectangle Rectangle 
    | ShapeCircle Circle

最佳答案

Michel Thoma 的回答在这里大放异彩。

您可以使用 Json.Decode.map 标记解码的值或 andThen像这样:

`andThen` \x -> decode (MyTag x)

使用这里是使用 andThen 的解决方案和 Json.Decode.Pipeline
import Json.Decode exposing ( Decoder, decodeString, int, andThen, oneOf )
import Json.Decode.Pipeline exposing ( decode, required )

import Html

main =
  let
    decoded = decodeString decodeShape "{ \"radius\": 2 }"
   in
     case decoded of
       Ok shape ->
         Html.text <| toString shape

       Err error ->
         Html.text error

type alias Rectangle = { width : Int, height : Int }

type alias Circle = { radius: Int }

type Shape
    = ShapeRectangle Rectangle
    | ShapeCircle Circle



decodeShape : Decoder Shape
decodeShape =
  oneOf
    [ decodeRectangle `andThen` \x -> decode (ShapeRectangle x)
    , decodeCircle `andThen` \x -> decode (ShapeCircle x)
    ]



decodeRectangle : Decoder Rectangle
decodeRectangle =
    decode Rectangle
        |> required "width" int
        |> required "height" int




decodeCircle : Decoder Circle
decodeCircle =
    decode Circle
         |> required "radius" int

关于json - 如何在 Elm 中解码标记的联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193642/

相关文章:

java - sun.misc.BASE64Decoder 是线程安全的吗?

json - Swift json 使用动态键解码

javascript - 如何将 json 转换为 javascript 数组?

Python Folium Choropleth 图

comparison - 如何比较 Elm 中的多个字段?

function - 如何在 Elm 中部分应用具有所需顺序的函数?

elm - GroupBy 使用 Elm 中的记录列表

安卓 : Synchronous way to use asyncttask : Json upload issue

java - 部署具有 JSON 文件的 Java 项目的正确方法是什么?

c++ - 如何使用 FFMPEG sws_scaler api 从 AV_PIX_FMT_VAAPI 转换为 AV_PIX_FMT_YUV420?