我如何从两个json字段解码自定义类型?

问题描述 投票:0回答:1

我正在使用postgrest(后端)和elm(前端)构建应用程序,现在我一直在写解码器。我不太了解如何解码为特定类型,而不是像int和string这样的基本类型解码器。

[当我查看stringimplemented的方式(第73至75行)时,它只是对Elm.Kernel.Json.decodeString的调用,而该调用又位于elm的js库中。

我的JSON看起来像这样:

{ "id" : 1
, "parent_id" : 1
, "body" : "text of my body"
}

OR

{ "id" : 1
, "parent_id" : 1
, "sub_parent_id" : 2
}

是否可以将类似的内容解码为单个记录类型(Step),其中包含具有多个构造函数的自定义类型,以匹配两个不同的字段(sub_parent_idbody)我的解码器看起来像这样,但是没有compile

import Api.Parent.Step.Types exposing ( Step, StepContent )
import Json.Decode exposing (..)
import Json.Decode.Pipeline exposing (..)

decoder : Decoder Step
decoder = 
    succeed Step
        |> required "id" int
        |> oneOf
            [ field "stepContent" stepBodyDecoder
            , field "stepContent" subStepDecoder
            ]

stepBodyDecoder : Decoder StepContent
stepBodyDecoder = 
    succeed StepContent
        |> required "body" string

subStepDecoder : Decoder StepContent
subStepDecoder =
    succeed StepContent
        |> required "sub_parent_id" decoder

我的任何类型:

module Api.Parent.Step.Types exposing ( Step, StepContent )

type StepContent 
    = StepBody String
    | SubStep Step

type alias Step =
    { id : Int
    , stepContent : StepContent
    }
json elm
1个回答
1
投票

JSON解码管道期望succeed被传递一个函数,StepContent不是一个函数,而是一个类型。变量构造函数是函数,但是,如果您看到编译器错误,则表明正确的修复方法(尽管这有点巧合,因为它只是基于相似的名称而提出):

I cannot find a `StepContent` variant:

28|     succeed StepContent
                ^^^^^^^^^^^
These names seem close though:

    StepBody
    Step
    OneOf
    SubStep

StepBodySubStep是您应该改用的。 stepBodyDecoder仅适用于该更改,并且使用subStepDecoder至少可以使您更进一步,但是类型和解码器否则与JSON不匹配。 sub_parent_id是数字,而不是对象,因此似乎SubStep应该采用Int而不是Step。然后,您可以在后续步骤中构造一个单独的分层数据结构。

© www.soinside.com 2019 - 2024. All rights reserved.