我有一个带有嵌套列表的类型别名,我想用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?
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?
You'll need to pass a decoder to Decode.list. In your case, it'll be a custom one based on the shape of your Student type.
This hasn't been tested, but something like the following should work:
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)
Run Code Online (Sandbox Code Playgroud)
See this post on writing custom flag decoders which should be instructive.
| 归档时间: |
|
| 查看次数: |
824 次 |
| 最近记录: |