Elm:如何从JSON API解码数据 [英] Elm: How to decode data from JSON API

查看:124
本文介绍了Elm:如何从JSON API解码数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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,但不知道如何.

I want to decode the json into a Collection, but don't know how.

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

如何实现解码器?谢谢

推荐答案

N.B. Json.Decode文档

尝试一下:

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.toInt返回了customDecoder所期望的Result,但是有足够的灵活性,您可以变得更复杂一些,并接受两者.通常情况下,您会使用map进行此类操作; customDecoder本质上是map用于可能失败的功能.

The tricky part is using stringToInt to turn string fields into integers. I've followed the API example in terms of what is an int and what is a string. We luck out a little that String.toInt returns a Result as expected by customDecoder but there's enough flexibility that you can get a little more sophisticated and accept both. Normally you'd use map for this sort of thing; customDecoder is essentially map for functions that can fail.

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

The other trick was to use Decode.at to get inside the attributes child object.

这篇关于Elm:如何从JSON API解码数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆