我有一个数据类:
data MyData = MyData { a :: Int, b :: String }
instance ToJSON MyData where
....
instance FromJSON MyData where
....
我可以解析json中的单个对象:
get :: IO (Maybe MyData)
get = do
res <- getSingleItemHttp
return $ decode $ responseBody res
如何获取MyData列表?
get2 :: IO [MyData]
get2 = do
res <- getManyItemsHttp
--????
return $ decode $ responseBody res -- doesn't compile
我如何将responseBody解析为List
?
答案 0 :(得分:2)
它应该像传入数组一样工作(并作为列表解码),因此您可能只需要将签名更改为get2 :: IO (Maybe [MyData])
:
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Json where
import GHC.Generics
import Data.Aeson
import Data.Text
import Data.ByteString.Lazy
data MyData = MyData { a :: Int, b :: String }
deriving (Generic, Show)
instance FromJSON MyData
example :: ByteString
example = "[{ \"a\": 1, \"b\": \"Hello\" }, { \"a\": 2, \"b\": \"World\" }]"
λ> decode example :: Maybe [MyData]
Just [MyData {a = 1, b = "Hello"},MyData {a = 2, b = "World"}]
会是这样的:如果你试试
get :: [MyData]
get = decode example
编译器会抱怨
无法将预期类型
匹配[MyData]
与实际类型Maybe a0
...
应该给你一个很大的提示。
您仍可以使用Data.Maybe.maybeToList
get :: [MyData]
get = Prelude.concat . maybeToList $ decode example