使用Elm中的对象解码Json数组

时间:2016-09-04 19:59:06

标签: json elm

我最近尝试使用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)

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

1 个答案:

答案 0 :(得分:21)

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

编辑:升级至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