问题描述
我正在尝试测试解码器 - 但我只能取回默认值。为文字墙道歉,但是当我尝试较小的示例时,它们总是有效,所以我猜这里某处存在一个愚蠢的错误。
我一直试图弄清楚为什么这会在很长一段时间内不起作用,但没有运气。 JSON 似乎是有效的(我尝试在 JS 和在线验证器中解析它)。
我尝试了不同的解码 JSON 的方法,但还是没有成功。
非常感谢任何帮助。如果问题中还需要添加任何内容,请告诉我(如果您不知道,我是榆树新手)。
我正在尝试解码如下所示的 JSON:
{
"fade": 1,"colour": "Campbells Red","stock": 1,"site": "","url": "","plastic":"DX","name":"aviar","seenAt":1612884837886,"weight":175,"compositeIdentifier":"aviar||Innova||DX||Campbells Red||175","manufacturer":"Innova","expiresAt":1615476837886,"glide":3,"turn":0,"speed":2,"price":8.99
}
我的类型是这样的:
type alias discSighting =
{ fade: Int,colour: String,stock: Int,site: String,url: String,plastic: String,name: String,weight: Int,compositeIdentifier: String,manufacturer: String,glide: Int,turn: Int,speed: Int,price: Float
}
我的解码器是这样的:
discDecoder: Decoder discSighting
discDecoder =
succeed discSighting
|> andMap (field "fade" (int) |> (withDefault) -1)
|> andMap (field "colour" (string) |> (withDefault) "")
|> andMap (field "stock" (int) |> (withDefault) -1)
|> andMap (field "site" (string) |> (withDefault) "")
|> andMap (field "url" (string) |> (withDefault) "")
|> andMap (field "plastic" (string) |> (withDefault) "")
|> andMap (field "name" (string) |> (withDefault) "")
|> andMap (field "weight" (int) |> (withDefault) -1)
|> andMap (field "compositeIdentifier" (string) |> (withDefault) "")
|> andMap (field "manufacturer" (string) |> (withDefault) "")
|> andMap (field "glide" (int) |> (withDefault) -1)
|> andMap (field "turn" (int) |> (withDefault) -1)
|> andMap (field "speed" (int) |> (withDefault) -1)
|> andMap (field "price" (float) |> (withDefault) -1)
我得到的错误是由于测试失败(它返回结果的错误方面,因此测试失败):
Err (Failure "Expecting an OBJECT with a field named price
)
解决方法
在 discDecoder
中,我不确定 andMap
和 withDefault
的定义是什么,但是 optional 包中的 NoRedInk/elm-json-decode-pipeline 函数会起作用andMap
和 withDefault
:
discDecoder : Decoder DiscSighting
discDecoder =
succeed DiscSighting
|> optional "fade" int -1
|> optional "colour" string ""
|> optional "stock" int -1
|> optional "site" string ""
|> optional "url" string ""
|> optional "plastic" string ""
|> optional "name" string ""
|> optional "weight" int -1
|> optional "compositeIdentifier" string ""
|> optional "manufacturer" string ""
|> optional "glide" int -1
|> optional "turn" int -1
|> optional "speed" int -1
|> optional "price" float -1