榆树:如何解码来自JSON API的数据

Seb*_*ian 18 json elm

我使用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
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有我的模特:

type alias Model = {
  id: Int,
  invitation: Int,
  name: String,
  provider: String,
  provider_user_id: Int
 }

 type alias Collection = List Model
Run Code Online (Sandbox Code Playgroud)

我想将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 =
  ?
Run Code Online (Sandbox Code Playgroud)

我如何实现解码器?谢谢

mgo*_*old 24

NB Json.Decode docs

试试这个:

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))
Run Code Online (Sandbox Code Playgroud)

棘手的部分是stringToInt用于将字符串字段转换为整数.我根据什么是int以及什么是字符串来遵循API示例.我们的运气稍微有点像预期的那样String.toInt返回Result,customDecoder但是有足够的灵活性,你可以得到一些更复杂和接受两者.通常你会用map这种东西; customDecoder主要map用于可能失败的功能.

另一个技巧是用来Decode.at进入attributes子对象.