Json.Decode.Pipeline列表(榆木0.18)

时间:2017-09-17 03:42:11

标签: json decode elm

我有一个带有嵌套列表的类型别名,我希望用Json.Decode.Pipeline进行解析。

import Json.Decode as Decode exposing (..)
import Json.Encode as Encode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

type alias Student =
    { name : String
    , age : Int
    }

type alias CollegeClass =
    { courseId : Int
    , title : String
    , teacher : String
    , students : List Student
    }

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> -- what goes here?

这是如何运作的?

1 个答案:

答案 0 :(得分:4)

您需要将解码器传递给Decode.list。在您的情况下,它将是基于Student类型的形状的自定义。

这尚未经过测试,但类似以下的内容应该工作:

studentDecoder =
    decode Student
        |> required "name" Decode.string
        |> required "age" Decode.int

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> Pipeline.required "students" (Decode.list studentDecoder)

有关编写自定义标记解码器的信息,请参阅this帖子。