我在解码JSON字符串中的可选字段时遇到了一些问题。我正在尝试解码"规划"计划可以是两种类型,正常计划或弹性计划。如果是正常计划,则它将具有planning_id
,如果是灵活计划,则它将具有flexplanning_id
。在我将存储计划的记录中,planningId
和fiexplanningId
都属于Maybe 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中,有两个规划,一个具有planning_id,另一个具有flexplanning_id。但是,在解码器产生的记录中,第一个规划既有planningId又有flexplanningId,而第二个规则既没有。
答案 0 :(得分:2)
您需要在解码器中翻转这两行以匹配它们的定义顺序:
|> optional "employee_timeslot_id" (nullable int) Nothing
|> optional "flexplanning_id" (nullable int) Nothing
它们按此顺序定义:
, flexplanningId : Maybe Int
, employeeTimeslotId : Maybe Int