首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Elm:如何从JSON API解码数据

Elm:如何从JSON API解码数据
EN

Stack Overflow用户
提问于 2015-09-15 06:36:43
回答 1查看 6.6K关注 0票数 18

我有使用http://jsonapi.org/格式的数据:

代码语言:javascript
复制
{
    "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
            }
        }
    ]
}

我的模型如下:

代码语言:javascript
复制
type alias Model = {
  id: Int,
  invitation: Int,
  name: String,
  provider: String,
  provider_user_id: Int
 }

 type alias Collection = List Model

我想把json解码成一个Collection,但是不知道怎么解码。

代码语言:javascript
复制
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 =
  ?

如何实现解码器?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-15 12:24:23

注意:Json.Decode docs

试试这个:

代码语言:javascript
复制
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子对象。

票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32575003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档