我有带有默认值的标志解码器。
flagsDecoder : Decode.Decoder Params
flagsDecoder =
Decode.map8 Params
(Decode.field "field1" (Decode.string) |> (Decode.withDefault) "1")
(Decode.field "field2" (Decode.string) |> (Decode.withDefault) "2")
(Decode.field "field3" (Decode.string) |> (Decode.withDefault) "3")
(Decode.field "field4" (Decode.string) |> (Decode.withDefault) "4)
(Decode.field "field5" (Decode.string) |> (Decode.withDefault) "5")
(Decode.field "field6" (Decode.int) |> (Decode.withDefault) 6)
(Decode.field "field7" (Decode.string) |> (Decode.withDefault) "7")
(Decode.field "field8" (Decode.string) |> (Decode.withDefault) "8")
如何添加更多字段?我有一个包含10个字段的JSON对象。
答案 0 :(得分:11)
我建议使用andMap
中的elm-community/json-extra
:
flagsDecoder : Decode.Decoder Params
flagsDecoder =
Decode.succeed Params
|> Decode.andMap (Decode.field "field1" (Decode.string) |> (Decode.withDefault) "1")
|> Decode.andMap (Decode.field "field2" (Decode.string) |> (Decode.withDefault) "2")
|> Decode.andMap (Decode.field "field3" (Decode.string) |> (Decode.withDefault) "3")
|> Decode.andMap (Decode.field "field4" (Decode.string) |> (Decode.withDefault) "4")
|> Decode.andMap (Decode.field "field5" (Decode.string) |> (Decode.withDefault) "5")
|> Decode.andMap (Decode.field "field6" (Decode.int) |> (Decode.withDefault) "6")
|> Decode.andMap (Decode.field "field7" (Decode.string) |> (Decode.withDefault) "7")
|> Decode.andMap (Decode.field "field8" (Decode.string) |> (Decode.withDefault) "8")
但是还有其他选项,例如elm-json-decode-pipeline
和a new experimental API。 andMap
确实非常简单明了,可以根据需要与mapN
一起使用并切换到DAX
。