2016-09-04 2 views
6

최근 Elm의 Http 모듈을 사용하여 서버에서 데이터를 가져 오려고 시도했으며 Elm의 사용자 정의 유형에 json을 디코딩하는 데 어려움을 겪고 있습니다.Elm의 객체를 사용하여 Json Array 디코드

내 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

당신은 먼저 사람의 디코더에

편집과 유사한 주소 디코더가 필요합니다

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

addressDecoder : Decoder Address 
addressDecoder = 
    JD.map3 Address 
    (field "id" int) 
    (field "city" string) 
    (field "street" string) 

느릅 나무 0.18로 업그레이드 그런 다음 "주소"필드에 그것을 사용할 수 있습니다

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

감사합니다. 그렇지만 어떻게 조합하여 Person 목록을 디코딩 할 수 있습니까? – rubiktubik

+1

목록 디코더를 포함하도록 답변을 업데이트했습니다. –

+0

감사합니다! 아주 좋은 해결책! – rubiktubik