2016-09-04 38 views
6

我最近試圖從Elm的Http模塊從服務器獲取數據,我堅持解碼JSON到Elm中的自定義類型。解碼JSON數組與埃爾姆中的對象

我的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) 

對於前兩個屬性,但我如何整合嵌套的地址屬性,以及如何結合這解碼t他列出?

回答

14

首先,您需要類似的地址譯碼器到你的個人解碼器

編輯:升級到榆樹0.18

import Json.Decode as JD exposing (field, Decoder) 

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 
+0

好的,謝謝,但我怎麼能結合他們解碼人名單? – rubiktubik

+1

我更新了包含列表解碼器的答案 –

+0

謝謝!很好的解決方案! – rubiktubik