Elm Json.Decode.Pipeline出现问题,可选

Elm Json.Decode.Pipeline出现问题,可选,elm,Elm,从JSON字符串解码可选字段时遇到一些问题。我试图解读“计划”,计划可以有两种类型,一种是普通计划,一种是弹性计划。如果是正常计划,它将有一个planning\u id,如果是弹性计划,它将有一个flexplanning\u id。在我将存储计划的记录中,planningId和fiexplanningId都是类型,可能是Int type alias Planning = { time : String , planningId : Maybe Int , groupId

从JSON字符串解码可选字段时遇到一些问题。我试图解读“计划”,计划可以有两种类型,一种是普通计划,一种是弹性计划。如果是正常计划,它将有一个
planning\u id
,如果是弹性计划,它将有一个
flexplanning\u id
。在我将存储计划的记录中,
planningId
fiexplanningId
都是
类型,可能是Int

type alias Planning =
    { time : String
    , planningId : Maybe Int
    , groupId : Int
    , groupName : String
    , flex : Bool
    , flexplanningId : Maybe Int
    , employeeTimeslotId : Maybe Int
    , employeeId : Int
    }
这是我使用的解码器:

planningDecoder : Decoder Planning
planningDecoder =
    decode Planning
        |> required "time" string
        |> optional "planning_id" (nullable int) Nothing
        |> required "group_id" int
        |> required "group_name" string
        |> required "flex" bool
        |> optional "employee_timeslot_id" (nullable int) Nothing
        |> optional "flexplanning_id" (nullable int) Nothing
        |> required "employee_id" int
但是,解码器没有准确地解码和存储来自JSON的数据。这里有一个例子。这是我的应用程序请求返回的字符串的一部分:

"monday": [
{
"time": "07:00 - 17:00",
"planning_id": 6705,
"group_name": "De rode stip",
"group_id": 120,
"flex": false,
"employee_timeslot_id": 1302,
"employee_id": 120120
},
{
"time": "07:00 - 17:00",
"group_name": "vakantie groep",
"group_id": 5347,
"flexplanning_id": 195948,
"flex": true,
"employee_id": 120120
}
],
然而,这是解码器的结果:

{ monday = [
  { time = "07:00 - 17:00"
  , planningId = Just 6705
  , groupId = 120
  , groupName = "De rode stip"
  , flex = False, flexplanningId = Just 1302
  , employeeTimeslotId = Nothing
  , employeeId = 120120 }
 ,{ time = "07:00 - 17:00"
  , planningId = Nothing
  , groupId = 5347
  , groupName = "vakantie groep"
  , flex = True
  , flexplanningId = Nothing
  , employeeTimeslotId = Just 195948
  , employeeId = 120120 
  }
 ],

如您所见,在JSON中,有两个计划,一个带有计划id,另一个带有flexplanning id。但是,在解码器生成的记录中,第一个计划既有计划id也有flexplanningId,而第二个计划既没有

您需要在解码器中翻转这两行,以匹配它们的定义顺序:

|> optional "employee_timeslot_id" (nullable int) Nothing
|> optional "flexplanning_id" (nullable int) Nothing
它们按以下顺序定义:

, flexplanningId : Maybe Int
, employeeTimeslotId : Maybe Int