如何在Elm中解码带标签的联合类型? [英] How to decode tagged union types in Elm?

查看:92
本文介绍了如何在Elm中解码带标签的联合类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有某种标记的联合类型,例如此处的Shape,我将如何在Elm中为其构造JSON解码器?

If I have a certain tagged union type, like Shape here, how would I construct a JSON decoder for it in Elm?

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

type alias Circle = { radius: Int }

type Shape 
    = ShapeRectangle Rectangle 
    | ShapeCircle Circle

推荐答案

给出您的JSON外观

{ "radius" : 10 }

{ "width" : 20, "height" : 15}

然后这将解决问题

import Json.Decode as Json exposing ((:=))

decodeShape : Json.Decoder Shape
decodeShape =
  Json.oneOf
    [ decodeShapeRectangle
    , decodeShapeCircle
    ]

decodeShapeRectangle : Json.Decoder Shape
decodeShapeRectangle =
  Json.map ShapeRectangle <|
    Json.object2 Rectangle
       ("width" := Json.int)
       ("height" := Json.int)


decodeShapeCircle : Json.Decoder Shape
decodeShapeCircle =
    Json.object1 (ShapeCircle << Circle)
         ("radius" := Json.int)

还有两件事:我经常添加一个'type'和'tag'字段,以在我使用通用字段名称的数据类型时帮助消除歧义. JSON如下所示:

A couple of additional things: I often add a 'type' and 'tag' field to help disambiguate when I have data types with common field names. The JSON then looks like

{ "type":"shape", "tag":"circle", "radius":10 }

此外,我认为在即将发布的0.18版本中,:=将替换为field.

Also, I think := will be replaced by field in the upcoming 0.18 release.

此致

迈克尔

这篇关于如何在Elm中解码带标签的联合类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆