我有一个带有嵌套列表的类型别名,我想用 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?
这是如何运作的?
最佳答案
您需要将解码器传递给 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 帖子,这应该具有指导意义。
关于列表中的 Json.Decode.Pipeline (elm 0.18),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46260418/