榆树简单JSON列表解码

时间:2017-09-26 13:05:07

标签: json elm

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

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

如何解决此错误?

1 个答案:

答案 0 :(得分:3)

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

修改:根据您的评论并重新阅读您的问题:

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

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

原始答案:

如果您想匹配decodeSessionResponse的类型签名并返回Decoder (List Session),那么您只需返回list decodeSession

decodeSessionResponse : Decoder (List Session)
decodeSessionResponse =
    list decodeSession

我怀疑你宁愿返回一个Decoder SessionResponse,可以这样定义:

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