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

时间:2015-09-14 22:36:43

标签: 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
            }
        }
    ]
}

我有我的模特:

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 =
  ?

如何实现解码器?感谢

1 个答案:

答案 0 :(得分:24)

N.B。 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))

棘手的部分是使用stringToInt将字符串字段转换为整数。我已经按照什么是int和什么是字符串来遵循API示例。我们很幸运String.toIntResult的预期返回customDecoder,但有足够的灵活性,您可以获得更复杂一点并接受两者。通常你会使用map来做这类事情;对于可能失败的函数,customDecoder基本上是map

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