我有一个地图,其中的关键是一种新型文本。我想自动(尽可能)为这个 Map 派生ToJSON和FromJSON。aeson已经为 Map Text v 提供了 ToJSON 和 FromJSON 的实例。
我的详细代码有效:
{-# LANGUAGE DeriveGeneric #-}
module Test where
import ClassyPrelude
import Data.Aeson
import GHC.Generics (Generic)
import qualified Data.Map as M
newtype MyText = MyText {unMyText::Text} deriving (Eq, Ord)
data Bar = Bar deriving (Generic)
instance ToJSON Bar
instance FromJSON Bar
data Foo = Foo (Map MyText Bar)
instance ToJSON Foo where
toJSON (Foo x) = toJSON mp
where mp = M.fromList . map (\(x,y) -> (unMyText x,y)) . M.toList $ x
instance FromJSON Foo where
parseJSON v = convert <$> parseJSON v
where convert :: Map Text Bar -> Foo
convert = Foo . mapFromList . map (\(x,y) -> (MyText x,y)) . mapToList
我可以做更多类似以下的事情吗?
data Foo = Foo (Map MyText Bar) deriving (Generic)
instance ToJSON Foo
instance FromJSON Foo
编辑
我试过(但仍然没有运气):
newtype MyText = MyText {unMyText::Text} deriving (Eq, Ord, ToJSON, FromJSON)
instance ToJSON Foo where
toJSON (Foo x) = toJSON x
和
newtype MyText = MyText {unMyText::Text} deriving (Eq, Ord, ToJSON, FromJSON)
instance ToJSON Foo