我有使用http://jsonapi.org/格式的数据:
{
"data": [
{
"type": "prospect",
"id": "1",
"attributes": {
"provider_user_id": "1",
"provider": "facebook",
"name": "Julia",
"invitation_id": 25
}
},
{
"type": "prospect",
"id": "2",
"attributes": {
"provider_user_id": "2",
"provider": "facebook",
"name": "Sam",
"invitation_id": 23
}
}
]
}
我的模型如下:
type alias Model = {
id: Int,
invitation: Int,
name: String,
provider: String,
provider_user_id: Int
}
type alias Collection = List Model
我想把json解码成一个Collection,但是不知道怎么解码。
fetchAll: Effects Actions.Action
fetchAll =
Http.get decoder (Http.url prospectsUrl [])
|> Task.toResult
|> Task.map Actions.FetchSuccess
|> Effects.task
decoder: Json.Decode.Decoder Collection
decoder =
?
如何实现解码器?谢谢
发布于 2015-09-15 12:24:23
试试这个:
import Json.Decode as Decode exposing (Decoder)
import String
-- <SNIP>
stringToInt : Decoder String -> Decoder Int
stringToInt d =
Decode.customDecoder d String.toInt
decoder : Decoder Model
decoder =
Decode.map5 Model
(Decode.field "id" Decode.string |> stringToInt )
(Decode.at ["attributes", "invitation_id"] Decode.int)
(Decode.at ["attributes", "name"] Decode.string)
(Decode.at ["attributes", "provider"] Decode.string)
(Decode.at ["attributes", "provider_user_id"] Decode.string |> stringToInt)
decoderColl : Decoder Collection
decoderColl =
Decode.map identity
(Decode.field "data" (Decode.list decoder))
棘手的部分是使用stringToInt
将字符串字段转换为整数。我遵循了API示例,了解了什么是int,什么是string。正如customDecoder
所期望的那样,String.toInt
返回了一个Result
,这是我们的一点幸运,但是它有足够的灵活性,您可以变得更复杂一点,并同时接受这两种方法。通常情况下,您会使用map
来处理这类事情;对于可能失败的函数,customDecoder
本质上是map
。
另一个技巧是使用Decode.at
进入attributes
子对象。
https://stackoverflow.com/questions/32575003
复制相似问题