我在 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/