当前位置:  开发笔记 > 前端 > 正文

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

如何解决《使用Aeson/JSON自动派生自定义数据类型的实例》经验,为你挑选了1个好方法。

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

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

{-# LANGUAGE DeriveGeneric #-}

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

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有