Elm Language
사용자 정의 JSON 디코더
수색…
소개
Json.Decode를 사용하여 사용자 정의 디코더를 만드는 방법 (예 : 공용체 유형 및 사용자 정의 데이터 유형으로 디코딩)
유니온 타입으로 디코딩
import Json.Decode as JD
import Json.Decode.Pipeline as JP
type PostType = Image | Video
type alias Post = {
id: Int
, postType: PostType
}
-- assuming server will send int value of 0 for Image or 1 for Video
decodePostType: JD.Decoder PostType
decodePostType =
JD.int |> JD.andThen (\postTypeInt ->
case postTypeInt of
0 ->
JD.succeed Image
1 ->
JD.succed Video
_ ->
JD.fail "invalid posttype"
)
decodePostMap : JD.Decoder Post
decodePostMap =
JD.map2 Post
(JD.field "id" JD.int)
(JD.field "postType" decodePostType)
decodePostPipline : JD.Decoder Post
decodePostPipline =
JP.decode Post
|> JP.required "id" JD.int
|> JP.required "postType" decodePostType
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow