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

时间:2016-02-29 06:51:55

标签: json haskell generics aeson custom-data-type

如果我有自定义数据类型用于使用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.

我做错了什么?

1 个答案:

答案 0 :(得分:12)

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

{-# LANGUAGE DeriveGeneric #-}

位于文件顶部,或使用-XDeriveGeneric标志进行编译。