Elm JSON解码器,用于带有数据的联合类型 [英] Elm JSON decoder for Union type with data
问题描述
我的json看起来像这样:
My json looks like this:
{"name": "providerWithVal", "value": "example"}
或类似这样:
{"name": "provider2"}
或
{"name": "provider3"}
我的Elm联合类型的定义如下:
My Elm union type is defined like so:
type Provider
= ProviderWithVal String
| Provider2
| Provider3
我可以为联合类型编写一个解码器,而无需附加数据.但是ProviderWithVal
需要一个字符串,我不确定如何使其全部正常工作.
I can write a decoder for a union type without data attached. But ProviderWithVal
takes a string and I'm not sure how to make it all work.
这是我到目前为止所拥有的:
This is what I have so far:
import Json.Decode as D
providerDecoder : D.Decoder Provider
providerDecoder =
D.field "name" D.string |> D.andThen providerNameDecoder
providerNameDecoder : String -> D.Decoder Provider
providerNameDecoder string =
case string of
"providerWithVal" -> D.succeed ProviderWithVal
"provider2" -> D.succeed Provider2
"provider3" -> D.succeed Provider3
_ -> D.fail <| "Invalid provider: " ++ string
推荐答案
您的问题的快速解决方案是将D.succeed ProviderWithVal
替换为D.map ProviderWithVal (D.field "value" Decode.string
The quick solution to your question is to replace D.succeed ProviderWithVal
with D.map ProviderWithVal (D.field "value" Decode.string
但是我会创建一个帮助程序来匹配目标字符串,然后按以下方式使用它:
But I would create a helper to match the target strings, and then use that in the following way:
decoder =
Decode.oneOf [ decodeWithVal, decodeP2, decodeP3 ]
decodeWithVal =
exactMatch (Decode.field "name" Decode.string)
"providerWithVal"
(Decode.map ProviderWithVal <| Decode.field "value" Decode.string)
decodeP2 =
exactMatch (Decode.field "name" Decode.string) "provider2" (Decode.succeed Provider2)
decodeP3 =
exactMatch (Decode.field "name" Decode.string) "provider3" (Decode.succeed Provider3)
exactMatch : Decoder String -> String -> Decoder a -> Decoder a
exactMatch matchDecoder match dec =
matchDecoder
|> Decode.andThen
(\str ->
if str == match then
dec
else
Decode.fail <| "[exactMatch] tgt: " ++ match ++ " /= " ++ str
)
这篇关于Elm JSON解码器,用于带有数据的联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!