2017-09-26 61 views
2

我有一个简单的结构,我需要能够解码,但我有问题。Elm简单的JSON列表解码

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

我该如何解决这个错误?

回答

3

有几种方法可以根据您要做的事情来处理此问题。

编辑:基于您的评论和你的问题的重新解读:

你指出API响应是会话的阵列,这意味着你可以使用Json.Decode.map映射一个list 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) 
+0

谢谢你,我宁愿使用第二种方法,但由于该列表是不在JSON响应中标记我无法使其工作。 – James

+0

我已更新答案,针对您提供的输入进行工作 –