用 Elm 中的对象解码 Json 数组
Decode Json Array with objects in 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)
前两个属性,但我如何整合嵌套地址 属性 以及如何结合它来解码列表?
您首先需要一个类似于个人解码器的地址解码器
编辑:升级到 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)
然后您可以将其用于 "address" 字段:
personDecoder: Decoder Person
personDecoder =
JD.map3 Person
(field "id" int)
(field "name" string)
(field "address" addressDecoder)
可以这样解码人员列表:
personListDecoder : Decoder (List Person)
personListDecoder =
JD.list personDecoder
我最近尝试使用 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)
前两个属性,但我如何整合嵌套地址 属性 以及如何结合它来解码列表?
您首先需要一个类似于个人解码器的地址解码器
编辑:升级到 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)
然后您可以将其用于 "address" 字段:
personDecoder: Decoder Person
personDecoder =
JD.map3 Person
(field "id" int)
(field "name" string)
(field "address" addressDecoder)
可以这样解码人员列表:
personListDecoder : Decoder (List Person)
personListDecoder =
JD.list personDecoder