用Elm中的对象解码Json Array [英] Decode Json Array with objects in Elm

查看:149
本文介绍了用Elm中的对象解码Json Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently tried to get data from server with Elm's Http module and i'm stuck with decoding json to custom types in Elm.

我的JSON看起来像这样:

My JSON looks like that:

[{
    "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
 }

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

What i found so far is that i need to write a decoder function:

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

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

That for the first two properties but how i integrate the nested Address property and how combine this to decode the list?

推荐答案

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

You first need an Address Decoder similar to your Person Decoder

升级到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)

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

Then you can use that for the "address" field:

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

可以这样解码人员名单:

A list of persons can be decoded like this:

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

这篇关于用Elm中的对象解码Json Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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