我正在研究这种类型的递归树
type Node anyType
= Leaf Id (Maybe anyType) Name
| Tree Id (List (Node anyType)) Name
在哪里
type Id
= Id Int
| Root
我正在尝试将这种json解码成它
{
"id": "root",
"entries": [
{
"id": 1,
"value": 0,
"name": "New Entry"
},
{
"id": 2,
"entries": [
{
"id": 4,
"value": 0,
"name": "New Entry"
}
],
"name": "New Entry"
}
],
"name": "Budget"
}
要解码 Id 类型,我正在使用这些解码器
rootDecoder =
(Decode.field "id" Decode.string)
|> Decode.andThen
(\str ->
if str == "root" then
(Decode.succeed Root)
else
Decode.fail <| "[exactMatch] tgt: " ++ "root" ++ " /= " ++ str
)
intIdDecoder =
Decode.map Id (Decode.field "id" Decode.int)
idDecoder =
Decode.oneOf
[ rootDecoder
, intIdDecoder
]
为了解码树结构,我尝试了以下方法,使用 Json.Decode.Pipeline:
leafDecoder valueDecoder =
Decode.succeed Leaf
|> required "id" idDecoder
|> required "value" valueDecoder
|> required "name" Decode.string
treeDecoder valueDecoder =
Decode.succeed Tree
|> required "id" idDecoder
|> required "entries"
(Decode.list
(Decode.lazy
(\_ ->
Decode.oneOf
[ leafDecoder valueDecoder
, treeDecoder valueDecoder
]
)
)
)
|> required "name" Decode.string
但是当我尝试解码结构时,出现以下错误:
The Json.Decode.oneOf at json.budget.entries[0] failed in the following 2 ways: (1) The Json.Decode.oneOf at json.id failed in the following 2 ways: (1) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: { "id": 1, "value": 0, "name": "New Entry" } Expecting an OBJECT with a field named `entries`
但我不明白为什么,因为这两个领域id
都entries
在那里,但它却抱怨。
我究竟做错了什么?
在此先感谢您的帮助