我使用Elm 0.19.1和NoRedInk / elm-json-decode-pipeline / 1.0.0
我的飞机类型是
type alias Aircraft = {name:String}
为此,我有以下解码器:
aircraftDecoder : Json.Decode.Decoder Aircraft
aircraftDecoder =
Json.Decode.succeed Aircraft
|> Json.Decode.Pipeline.required "name" Json.Decode.string
不幸的是,解码器抱怨我说:“ BadBody”给定值的问题:(...)“这是因为实际上我感兴趣的区域周围充满了噪音(来自HATEOAS api),就像这样:
{
"_embedded" : {
"aircrafts" : [ {
"name" : "AC01",
"_links" : {
"self" : {
"href" : "http://localhost:8080/aircrafts/1"
},
"aircraft" : {
"href" : "http://localhost:8080/aircrafts/1"
}
}
}, {
"name" : "AC01",
"_links" : {
"self" : {
"href" : "http://localhost:8080/aircrafts/2"
},
"aircraft" : {
"href" : "http://localhost:8080/aircrafts/2"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/aircrafts{?page,size,sort}",
"templated" : true
},
"profile" : {
"href" : "http://localhost:8080/profile/aircrafts"
}
},
"page" : {
"size" : 20,
"totalElements" : 4,
"totalPages" : 1,
"number" : 0
}
}
如何更改代码,并保持使用管道,以使解码器不会因所有这些噪声而丢失?
我听说过有关使用Json.Decode.at的一些信息,但文档不足以让我获得正确的代码。
以下应该起作用:
aircraftNameDecoder : Json.Decode.Decoder String
aircraftNameDecoder =
Json.Decode.map (Maybe.withDefault "" << List.head) <|
Json.Decode.at [ "_embedded", "aircrafts" ] <|
Json.Decode.list (Json.Decode.field "name" Json.Decode.string)
aircraftDecoder : Json.Decode.Decoder Aircraft
aircraftDecoder =
Json.Decode.succeed Aircraft
|> Json.Decode.Pipeline.custom aircraftNameDecoder