如果我有自定义数据类型用于使用Aeson解析JSON
data Response = Response { response :: [Body] } deriving (Show) instance FromJSON Response where parseJSON (Object v) = Response <$> v .: "response" parseJSON _ = mzero data Body = Body { body_id :: Int , brandId :: Int } deriving (Show) instance FromJSON Body where parseJSON (Object v) = Body <$> v .: "id" <*> v .: "brandId" parseJSON _ = mzero raw :: BS.ByteString raw = "{\"response\":[{\"id\":5977,\"brandId\":87}]}"
赠送:
?> decode raw :: Maybe Response Just (Response {response = [Body {body_id = 5977, brandId = 87}]})
如何FromJSON
自动派生实例?
我试过了:
data Response = Response { response :: [Body] } deriving (Show,Generic) data Body = Body { body_id :: Int , brandId :: Int } deriving (Show,Generic) instance FromJSON Response instance FromJSON Body
正如一些教程中所建议的那样,但这给出了:
?> :l response.hs
[1 of 1] Compiling Response ( response.hs, interpreted )
response.hs:19:22:
Can't make a derived instance of `Generic Response':
You need DeriveGeneric to derive an instance for this class
In the data declaration for `Response'
response.hs:24:22:
Can't make a derived instance of `Generic Body':
You need DeriveGeneric to derive an instance for this class
In the data declaration for `Body'
Failed, modules loaded: none.
我究竟做错了什么?
错误告诉您的是,您必须启用DeriveGeneric
扩展才能使其正常工作.所以你必须添加:
{-# LANGUAGE DeriveGeneric #-}
在文件的顶部,或使用-XDeriveGeneric
标志进行编译.