2015-09-14 11 views
17

からデータを復号化するために、私はhttp://jsonapi.org/形式を使用してこのデータを持っている:エルム:どのようなJSON API

{ 
    "data": [ 
     { 
      "type": "prospect", 
      "id": "1", 
      "attributes": { 
       "provider_user_id": "1", 
       "provider": "facebook", 
       "name": "Julia", 
       "invitation_id": 25 
      } 
     }, 
     { 
      "type": "prospect", 
      "id": "2", 
      "attributes": { 
       "provider_user_id": "2", 
       "provider": "facebook", 
       "name": "Sam", 
       "invitation_id": 23 
      } 
     } 
    ] 
} 

私は私のモデルを持っているように:私はコレクションにJSONをデコードしたい

type alias Model = { 
    id: Int, 
    invitation: Int, 
    name: String, 
    provider: String, 
    provider_user_id: Int 
} 

type alias Collection = List Model 

、しかし、どのようにわからない。

fetchAll: Effects Actions.Action 
fetchAll = 
    Http.get decoder (Http.url prospectsUrl []) 
    |> Task.toResult 
    |> Task.map Actions.FetchSuccess 
    |> Effects.task 

decoder: Json.Decode.Decoder Collection 
decoder = 
    ? 

デコーダを実装するにはどうすればよいですか?おかげで

答えて

22

N.B.トリッキーな部分は、整数に文字列フィールドをオンにするstringToIntを使用している

import Json.Decode as Decode exposing (Decoder) 
import String 

-- <SNIP> 

stringToInt : Decoder String -> Decoder Int 
stringToInt d = 
    Decode.customDecoder d String.toInt 

decoder : Decoder Model 
decoder = 
    Decode.map5 Model 
    (Decode.field "id" Decode.string |> stringToInt) 
    (Decode.at ["attributes", "invitation_id"] Decode.int) 
    (Decode.at ["attributes", "name"] Decode.string) 
    (Decode.at ["attributes", "provider"] Decode.string) 
    (Decode.at ["attributes", "provider_user_id"] Decode.string |> stringToInt) 

decoderColl : Decoder Collection 
decoderColl = 
    Decode.map identity 
    (Decode.field "data" (Decode.list decoder)) 

Json.Decode docs

はこれを試してみてください。 APIの例には、intとは何か、文字列は何かという点で守ってきました。我々はちょっと運が少しString.toIntcustomDecoderによってResult期待どおりに返しますが、少し洗練され、両方を受け入れることができる十分な柔軟性があります。通常、この種のものにはmapを使用します。 customDecoderは、機能しなくなる可能性がある本質的にはmapです。

もう1つのトリックは、を使用してattributes子オブジェクトを取得することでした。

+0

また、値を結果にマップする方法について説明した場合は役に立ちます。 –

+0

OPはデコーダの実装について尋ねました。 Resultを取得するには、 'Json.Decode.decodeString'または' decodeValue'を呼び出します。 – mgold

+2

Decode.object5はDecode.map5になりました – madnight

関連する問題