在Elm中编码和解码简单的自定义类型

问题描述 投票:0回答:1

这篇文章是关于如何在Elm中以以下格式编码和解码简单的自定义类型:

type MyCustomType
  = A
  | B
  | C
json elm custom-type
1个回答
0
投票

这是有关如何编码和解码任何自定义类型的快速简单的演示。

假设您具有这样的自定义类型:

type MyCustomType
  = A
  | B
  | C

您可以直接将MyCustomType编码为字符串:

encodeMyCustomType : MyCustomType -> Encode.Value
encodeMyCustomType myCustomType =
  Encode.string <|
    case myCustomType of
      A -> "A"
      B -> "B"
      C -> "C"

解码MyCustomType稍微复杂一些。您需要使用Decode.andThen检查找到的变体,并在没有找到有效变体的情况下使用Decode.andThen

Decode.fail
© www.soinside.com 2019 - 2024. All rights reserved.