2
我需要解碼一個JSON數組,其頭部項目的類型爲User
,所有尾部項目爲Nickname
's。數組長度事先不知道,我不能更改JSON表示。elm解碼非均勻陣列
JSON樣本:
{ "userdata" : [
{
"id" : 1,
"name" : "MyName",
"email" : "[email protected]"
},
{
"name" : "n1"
},
{
"name" : "n2"
}
]
}
我的類型定義:
module Decoders exposing (..)
type alias User =
{ id : Int
, name : String
, email : String
}
type alias Nickname =
{ name : String
}
type alias Model =
{ user : User
, nicknames : List Nickname
}
有在User
和Nickname
其他許多不同的領域,但我在這裏縮短它保持示例簡單。
解碼器:
decodeUser : Json.Decode.Decoder User
decodeUser =
Json.Decode.Pipeline.decode User
|> Json.Decode.Pipeline.required "id" (Json.Decode.int)
|> Json.Decode.Pipeline.required "name" (Json.Decode.string)
|> Json.Decode.Pipeline.required "email" (Json.Decode.string)
decodeNickname : Json.Decode.Decoder Nickname
decodeNickname =
Json.Decode.Pipeline.decode Nickname
|> Json.Decode.Pipeline.required "name" (Json.Decode.string)
decodeModel : Json.Decode.Decoder Model
decodeModel =
Json.Decode.Pipeline.decode Model
|> Json.Decode.Pipeline.required "userdata" (Json.Decode.index 0 decodeUser)
|> Json.Decode.Pipeline.hardcoded [ Nickname "Nick", Nickname "Names" ]
測試:
decodesModel : Test
decodesModel =
test "Decodes a user and list of nicknames" <|
\() ->
let
input =
"""
{ "userdata" : [
{
"id" : 1,
"name" : "MyName",
"email" : "[email protected]"
},
{
"name" : "n1"
},
{
"name" : "n2"
}
]
}
"""
decodedOutput =
Json.Decode.decodeString
Decoders.decodeModel
input
nicknames =
[ Decoders.Nickname "n1", Decoders.Nickname "n2" ]
user =
Decoders.User 1 "MyName" "[email protected]"
expectation =
Decoders.Model user nicknames
in
Expect.equal decodedOutput
(Ok expectation)
因爲我剛纔硬編碼的Nickname
deserialisation測試失敗:
✗ Decodes a user and list of nicknames
Ok { user = { id = 1, name = "MyName", email = "[email protected]" }, nicknames = [{ name = "n1" },{ name = "n2" }] }
╷
│ Expect.equal
╵
Ok { user = { id = 1, name = "MyName", email = "[email protected]" }, nicknames = [{ name = "Nick" },{ name = "Names" }] }
什麼是下降頭的最佳途徑項並將數組的其餘部分反序列化爲列表Nickname
的?
感謝,作品像一個魅力!很好的策略來解碼成模式匹配的Json.Decode.Value項目。 – Giraffen