我最近尝试使用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
}
}]
Run Code Online (Sandbox Code Playgroud)
哪个应解码为:
type alias Person =
{
id : Int,
name: String,
address: Address
}
type alias Address =
{
id: Int,
city: String,
street: String
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我发现的是我需要编写解码器功能:
personDecoder: Decoder Person
personDecoder =
object2 Person
("id" := int)
("name" := string)
Run Code Online (Sandbox Code Playgroud)
对于前两个属性,但我如何集成嵌套的Address属性以及如何组合它来解码列表?
Cha*_*ert 24
您首先需要一个类似于您的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)
Run Code Online (Sandbox Code Playgroud)
然后你可以将它用于"地址"字段:
personDecoder: Decoder Person
personDecoder =
JD.map3 Person
(field "id" int)
(field "name" string)
(field "address" addressDecoder)
Run Code Online (Sandbox Code Playgroud)
人员列表可以像这样解码:
personListDecoder : Decoder (List Person)
personListDecoder =
JD.list personDecoder
Run Code Online (Sandbox Code Playgroud)