Elm 简单 JSON 列表解码

Elm Simple JSON List Decoding

我有一个需要能够解码的简单结构,但我遇到了问题。

我的 API 回复如下所示:

[{"userId":70, "otherField":1, ...},
 {"userId":70, "otherField":1, ...},    
 {"userId":71, "otherField":1, ...}]

我正在尝试按如下方式对其进行解码:

type alias SessionResponse =
    { sessions : List Session
    }


type alias Session =
    { userId : Int
    }


decodeSessionResponse : Decoder (List Session)
decodeSessionResponse =
    decode Session
        |> list decodeSession -- Gives an Error


decodeSession : Decoder Session
decodeSession =
    decode Session
        |> required "userId" int

我看到的错误消息是:

The right side of (|>) is causing a type mismatch.

(|>) is expecting the right side to be a:

Decoder (Int -> Session) -> Decoder (List Session)

But the right side is:

Decoder (List Session)

 It looks like a function needs 1 more argument.

我该如何解决这个错误?

根据您的尝试,有几种方法可以解决这个问题。

编辑: 根据您的评论和对您问题的重新阅读:

您指出 API 响应是一组会话,这意味着您可以只使用 Json.Decode.maplist Session 映射到 SessionResponse:

decodeSessionResponse : Decoder SessionResponse
decodeSessionResponse =
     map SessionResponse (list decodeSession)

原答案:

如果你想匹配decodeSessionResponse和return的类型签名一个Decoder (List Session),那么你可以简单地return list decodeSession.

decodeSessionResponse : Decoder (List Session)
decodeSessionResponse =
    list decodeSession

我怀疑你更愿意return一个Decoder SessionResponse,可以这样定义:

decodeSessionResponse : Decoder SessionResponse
decodeSessionResponse =
    decode SessionResponse
        |> required "sessions" (list decodeSession)