Ответ 1
N.B. Json.Decode docs
Попробуйте следующее:
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))
Сложная часть использует stringToInt
, чтобы превратить строковые поля в целые числа. Я следовал примеру API с точки зрения того, что такое int и что такое строка. Нам немного повезло, что String.toInt
возвращает Result
, как ожидалось, customDecoder
, но при этом достаточно гибкости, что вы можете получить немного более сложную и принять оба. Обычно вы используете map
для такого рода вещей; customDecoder
по существу map
для функций, которые могут выйти из строя.
Другим трюком было использование Decode.at
для входа в дочерний объект attributes
.