on 1.1.1.0 help sign in
typeable/aeson/examples/TemplateHaskell.hs
28 lines 794 B history raw
1-- We can use Template Haskell (TH) to generate instances of the
2-- FromJSON and ToJSON classes automatically. This is the fastest way
3-- to add JSON support for a type.
4{-# LANGUAGE OverloadedStrings #-}
5{-# LANGUAGE TemplateHaskell #-}
7module Main (main) where
9import Prelude ()
10import Prelude.Compat
12import Data.Aeson (decode, encode)
13import Data.Aeson.TH (deriveJSON, defaultOptions)
14import qualified Data.ByteString.Lazy.Char8 as BL
16data Coord = Coord { x :: Double, y :: Double }
17 deriving (Show)
19-- This splice will derive instances of ToJSON and FromJSON for us.
21$(deriveJSON defaultOptions ''Coord)
23main :: IO ()
24main = do
25 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
26 print req
27 let reply = Coord { x = 123.4, y = 20 }
28 BL.putStrLn (encode reply)