簡體   English   中英

在Haskell中解析RoseTree JSON

[英]Parsing RoseTree JSON in 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解析器定義有什么問題,我該如何解決? 謝謝!

您需要縮進toJSON的定義

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

您忘記在instance ToJSON RoseTree2之后縮進行,因此實例塊已關閉,並且默認為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM