【发布时间】:2021-02-11 13:12:09
【问题描述】:
我正在尝试测试解码器 - 但我只能取回默认值。为文字墙道歉,但是当我尝试较小的示例时,它们总是有效,所以我猜这里某处存在愚蠢的错误。
我一直在试图弄清楚为什么这在很长一段时间内都行不通,但没有运气。 JSON 似乎是有效的(我尝试在 JS 和在线验证器中解析它)。
我尝试了不同的 JSON 解码方法,但还是没有成功。
非常感谢任何帮助。如果应该在问题中添加任何其他内容,请告诉我(我是 elm 新手,如果你不知道的话)。
我正在尝试解码如下所示的 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(失败“期望一个带有名为
price的字段的对象 )
【问题讨论】:
-
您对
andMap和withDefault的定义是什么?你在用Json.Decode.Extra吗?尝试删除withDefaults 之一,看看它给出了什么错误。 -
@absynce 他们来自 Json.Decode.Extra,对不起,我应该说。当我删除
withDefault时,我得到一个错误,而不是 Ok 响应。下面的答案似乎能够解码对象,但是当我使用相同的代码时,它无法像我拥有的那样解码 JSON 字符串 -
您能否将错误响应的详细信息添加到您的问题中?
-
我现在已经加了(不过估计用处不大)
-
@absynce 原来我使用了错误的变量...不敢相信
标签: elm