Blame examples/Generic.hs
|
Packit |
9a2dfb |
-- This example is basically the same as in Simplest.hs, only it uses
|
|
Packit |
9a2dfb |
-- GHC's builtin generics instead of explicit instances of ToJSON and
|
|
Packit |
9a2dfb |
-- FromJSON.
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
-- We enable the DeriveGeneric language extension so that GHC can
|
|
Packit |
9a2dfb |
-- automatically derive the Generic class for us.
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
{-# LANGUAGE DeriveGeneric #-}
|
|
Packit |
9a2dfb |
{-# LANGUAGE OverloadedStrings #-}
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
module Main (main) where
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
import Prelude ()
|
|
Packit |
9a2dfb |
import Prelude.Compat
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
import Data.Aeson (FromJSON, ToJSON, decode, encode)
|
|
Packit |
9a2dfb |
import qualified Data.ByteString.Lazy.Char8 as BL
|
|
Packit |
9a2dfb |
import GHC.Generics (Generic)
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
-- To decode or encode a value using the generic machinery, we must
|
|
Packit |
9a2dfb |
-- make the type an instance of the Generic class.
|
|
Packit |
9a2dfb |
data Coord = Coord { x :: Double, y :: Double }
|
|
Packit |
9a2dfb |
deriving (Show, Generic)
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
-- While we still have to declare our type as instances of FromJSON
|
|
Packit |
9a2dfb |
-- and ToJSON, we do *not* need to provide bodies for the instances.
|
|
Packit |
9a2dfb |
-- Default versions will be supplied for us.
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
instance FromJSON Coord
|
|
Packit |
9a2dfb |
instance ToJSON Coord
|
|
Packit |
9a2dfb |
|
|
Packit |
9a2dfb |
main :: IO ()
|
|
Packit |
9a2dfb |
main = do
|
|
Packit |
9a2dfb |
let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
|
|
Packit |
9a2dfb |
print req
|
|
Packit |
9a2dfb |
let reply = Coord { x = 123.4, y = 20 }
|
|
Packit |
9a2dfb |
BL.putStrLn (encode reply)
|