Advertisement
NLinker

Polymorphic Aeson serialization using Generic instances

May 25th, 2016
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE DeriveGeneric #-}
  2.  
  3. module Integration.TestAeson where
  4.  
  5. import Data.Aeson
  6. import GHC.Generics
  7.  
  8. data Pets = Dogs [Dog] | Cats [Cat] | Rodents [Rodent] | Reptiles [Reptile]
  9.   deriving (Show, Generic)
  10.  
  11. data Dog = Dog {
  12.   dogField :: String
  13. } deriving (Show, Generic)
  14.  
  15. data Cat = Cat {
  16.   catField :: String
  17. } deriving (Show, Generic)
  18.  
  19. data Rodent = Rodent {
  20.   rodentField :: String
  21. } deriving (Show, Generic)
  22.  
  23. data Reptile = Reptile {
  24.   reptileField :: String
  25. } deriving (Show, Generic)
  26.  
  27. data Person = Person {
  28.   name :: String,
  29.   species :: String,
  30.   pets :: Pets
  31. } deriving (Show,Generic)
  32.  
  33. instance ToJSON Cat
  34. instance FromJSON Cat
  35. instance ToJSON Dog
  36. instance FromJSON Dog
  37. instance ToJSON Rodent
  38. instance FromJSON Rodent
  39. instance ToJSON Reptile
  40. instance FromJSON Reptile
  41. instance ToJSON Pets
  42. instance FromJSON Pets
  43. instance ToJSON Person
  44. instance FromJSON Person
  45.  
  46. doit :: IO ()
  47. doit = do
  48.   let agerbil = Rodent "Ager"
  49.   let amouse = Rodent "Amose"
  50.   let me = Person "user5402" "Human" (Rodents [agerbil, amouse])
  51.   print $ encode me
  52.  
  53. {- run this
  54.  
  55. λ> doit
  56. "{\"species\":\"Human\",\"name\":\"user5402\",\"pets\":{\"tag\":\"Rodents\",\"contents\":[{\"rodentField\":\"Ager\"},{\"rodentField\":\"Amose\"}]}}"
  57.  
  58. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement