2016-11-10 67 views
1

我在解碼JSON字符串的可選字段時遇到了一些麻煩。我試圖解碼「計劃」,計劃可以分爲兩種類型,即正常計劃或靈活計劃。如果這是一個正常的計劃,它將有一個planning_id,如果它是一個彈性計劃,它將有一個flexplanning_id。在我將存儲計劃的記錄中,planningIdfiexplanningId的類型都是Maybe IntJson.Decode.Pipeline麻煩可選

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,而第二個既沒有。

回答

2

您需要在解碼器翻轉這兩行以匹配其定義的順序:

, flexplanningId : Maybe Int 
, employeeTimeslotId : Maybe Int 
+0

啊哈,愚蠢的錯誤:

|> optional "employee_timeslot_id" (nullable int) Nothing |> optional "flexplanning_id" (nullable int) Nothing 

它們的順序進行定義!感謝您的支持! –