json - 我如何 Json.decode 联合类型?

标签 json elm

我在 module Foo exposing (..) 中有一个像这样定义的类型:

type Foo
    = Bar
        { a : String
        , b : String
        }
    | Baz
        ...

然后我尝试创建一个 Json Decoder在一个单独的模块中解码该类型,如下所示:
barDecoder : Decoder Bar
barDecoder =
    map2 Bar
        (field "a" string)
        (field "b" string)

Elm 编译器在 map2 Bar 上给我一个错误。表示该类型 Bar 的行没有找到。包含解码器的模块有import Foo exposing (..) .我还尝试将此函数移动到包含类型定义的同一模块中并得到相同的错误,因此它与位于单独的模块中没有任何关系。

我试过把它改成 map2 Foo.Bar ,但这也不起作用。

像这样解码联合类型的正确方法是什么?

最佳答案

您应该使用 Json.Decode.oneOf如果你有多种解码 json 的方法。

这是如何使用它的示例。
(我编造了Baz,因为你没有指定它。)

import Json.Decode as Json

type Foo
    = Bar
        { a : String
        , b : String
        }
    | Baz Int


barDecoder : Json.Decoder Foo
barDecoder =
    Json.map2 (\x y -> Bar { a = x, b = y })
        (Json.field "a" Json.string)
        (Json.field "b" Json.string)


bazDecoder : Json.Decoder Foo
bazDecoder =
    Json.map Baz Json.int


fooDecoder : Json.Decoder Foo
fooDecoder =
    Json.oneOf [ barDecoder, bazDecoder ]

关于json - 我如何 Json.decode 联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969381/

相关文章:

javascript - 如何在 Rails 中的 Controller 操作成功或失败的 View 中显示 JSON 状态消息?

java - 如何从 JSON 数组中删除重复的 JSON 对象

Elm - 如何根据另一个信号修改一个信号的参数化

json - 解码 json 中的事物或事物列表

json - 如何将 Json.Decode.Value 解码为 elm 0.19 中的标记联合类型?

http - 在 Elm 中指定 Http header

java - 在结果 Json 响应中显示类名而不是对象

javascript - 我可以使用空字符串作为对象标识符吗?

jquery - 如何将 JSONP GET 请求与 OpenWeatherAPI 结合使用?

elm - 无法读取未定义的属性 'kids' - 或者如何打破 Elm 中信号的循环依赖关系?