使用Aeson/JSON自动派生自定义数据类型的实例

mat*_*ias 2 generics json haskell custom-data-type aeson

如果我有自定义数据类型用于使用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}]}"
Run Code Online (Sandbox Code Playgroud)

赠送:

?> decode raw :: Maybe Response
Just (Response {response = [Body {body_id = 5977, brandId = 87}]})
Run Code Online (Sandbox Code Playgroud)

如何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
Run Code Online (Sandbox Code Playgroud)

正如一些教程中所建议的那样,但这给出了:

?> :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.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Bak*_*riu 13

错误告诉您的是,您必须启用DeriveGeneric扩展才能使其正常工作.所以你必须添加:

{-# LANGUAGE DeriveGeneric #-}
Run Code Online (Sandbox Code Playgroud)

在文件的顶部,或使用-XDeriveGeneric标志进行编译.