【问题标题】:Decode Json Array with objects in Elm用 Elm 中的对象解码 Json 数组
【发布时间】:2017-01-12 06:07:23
【问题描述】:

我最近尝试使用 Elm 的 Http 模块从服务器获取数据,但我一直坚持将 json 解码为 Elm 中的自定义类型。

我的 JSON 看起来像这样:

[{
    "id": 1,
    "name": "John",
    "address": {
        "city": "London",
        "street": "A Street",
        "id": 1
    }
},
{
    "id": 2,
    "name": "Bob",
    "address": {
        "city": "New York",
        "street": "Another Street",
        "id": 1
    }
}]

应该解码为:

type alias Person =
{
 id : Int,
 name: String,
 address: Address
}

type alias Address = 
{
 id: Int,
 city: String,
 street: String
 }

到目前为止我发现我需要编写一个解码器函数:

personDecoder: Decoder Person
personDecoder =
  object2 Person
    ("id" := int)
    ("name" := string)

对于前两个属性,但是我如何集成嵌套的地址属性以及如何结合它来解码列表?

【问题讨论】:

    标签: json elm


    【解决方案1】:

    您首先需要一个类似于您的人员解码器的地址解码器

    编辑:升级到 Elm 0.18

    import Json.Decode as JD exposing (field, Decoder, int, string)
    
    addressDecoder : Decoder Address
    addressDecoder =
      JD.map3 Address
        (field "id" int)
        (field "city" string)
        (field "street" string)
    

    然后您可以将其用于“地址”字段:

    personDecoder: Decoder Person
    personDecoder =
      JD.map3 Person
        (field "id" int)
        (field "name" string)
        (field "address" addressDecoder)
    

    人员列表可以这样解码:

    personListDecoder : Decoder (List Person)
    personListDecoder =
      JD.list personDecoder
    

    【讨论】:

    • 你将如何将它与Task.performHttp.get 一起使用?使用 Http.get 时出现类型错误,它表示它不适用于 Decoder (List a),并且只能用于 Decoder a
    • @omouse - 没有看到你的代码,我只能猜测(听起来你可能在 Msg 中的类型参数不匹配,你正在发送成功函数) - 但你可能会得到更好的服务通过打开一个新问题或在 Slack 频道中询问是否不是这样
    • @ChadGilbert 将其作为问题发布:stackoverflow.com/questions/39628213/… 没有意识到有一个 Slack 频道,我一直在使用 IRC。
    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 2020-05-02
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多