on 0.8.1.1 help sign in
typeable/aeson/examples/TemplateHaskell.hs
25 lines 716 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.
5{-# LANGUAGE TemplateHaskell #-}
7{-# LANGUAGE OverloadedStrings #-}
9import Data.Aeson (decode, encode)
10import Data.Aeson.TH (deriveJSON, defaultOptions)
11import qualified Data.ByteString.Lazy.Char8 as BL
13data Coord = Coord { x :: Double, y :: Double }
14 deriving (Show)
16-- This splice will derive instances of ToJSON and FromJSON for us.
18$(deriveJSON defaultOptions ''Coord)
20main :: IO ()
21main = do
22 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
23 print req
24 let reply = Coord 123.4 20
25 BL.putStrLn (encode reply)