用Elm中的对象解码Json Array

编程入门 行业动态 更新时间:2024-10-25 18:29:03
本文介绍了用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

本文发布于:2023-08-03 08:09:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1285504.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Elm   Array   Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!