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

Automatically deriving instance for custom data type with Aeson/JSON

如果我有一个自定义数据类型可以用 AesonJSON 解析

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 标志进行编译。