on 0.8.0.0 help sign in
typeable/aeson/examples/TemplateHaskell.hs
29 lines 888 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.
17--
18-- The use of "id" below is a placeholder function to transform the
19-- names of the type's fields. We don't want to transform them, so we
20-- use the identity function.
22$(deriveJSON defaultOptions ''Coord)
24main :: IO ()
25main = do
26 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
27 print req
28 let reply = Coord 123.4 20
29 BL.putStrLn (encode reply)