在Haskell中解析RoseTree JSON

时间:2014-12-20 08:57:31

标签: json parsing haskell

我正在尝试解析RoseTree的JSON表示。这是我的快照:

module RoseTree2 where

import Data.Tree
import Data.Aeson
import qualified Data.Text as T
import Control.Applicative

data RoseTree2 = RoseNode Int [RoseTree2] deriving (Show)

instance ToJSON RoseTree2 where
toJSON (RoseNode n cs) =
    object [T.pack "value" .= show n
    , T.pack "children".= show cs]

instance FromJSON RoseTree2 where
    parseJSON (Object o) =
        RoseNode <$> o.: T.pack "value"
        <*> o.: T.pack "children"

但是我收到了关于文件加载的错误:

RoseTree2.hs:10:10:
    No instance for (GToJSON (GHC.Generics.Rep RoseTree2))
      arising from a use of `aeson-0.7.0.6:Data.Aeson.Types.Class.$gdmtoJSON'
    Possible fix:
      add an instance declaration for
      (GToJSON (GHC.Generics.Rep RoseTree2))
    In the expression:
      (aeson-0.7.0.6:Data.Aeson.Types.Class.$gdmtoJSON)
    In an equation for `toJSON':
        toJSON = (aeson-0.7.0.6:Data.Aeson.Types.Class.$gdmtoJSON)
    In the instance declaration for `ToJSON RoseTree2'
Failed, modules loaded: none.

请问有人告诉我我对JSON解析器的定义有什么问题,我该如何解决?谢谢!

2 个答案:

答案 0 :(得分:2)

您需要缩进toJSON

的定义
instance ToJSON RoseTree2 where
  toJSON (RoseNode n cs) =
    object [T.pack "value" .= show n
    , T.pack "children".= show cs]

答案 1 :(得分:1)

您忘记在instance ToJSON RoseTree2之后缩进该行,因此实例块已关闭,默认为

default toJSON :: (Generic a, GToJSON (Rep a)) => a -> Value
toJSON = genericToJSON defaultOptions