Skip to content
Newer
Older
100644 39 lines (27 sloc) 1.16 KB
a83da41 @bos Start working on release notes and expanded examples.
authored Nov 30, 2011
1 -- This example is basically the same as in Simplest.hs, only it uses
2 -- GHC's builtin generics instead of explicit instances of ToJSON and
3 -- FromJSON.
4
5 -- This example only works with GHC 7.2 or newer, as it uses the
6 -- datatype-generic programming machinery introduced in 7.2.
7
8 -- We enable the DeriveGeneric language extension so that GHC can
9 -- automatically derive the Generic class for us.
10
11 {-# LANGUAGE DeriveGeneric #-}
12
13 {-# LANGUAGE OverloadedStrings #-}
14
15 import Data.Aeson (FromJSON, ToJSON, decode, encode)
16 import qualified Data.ByteString.Lazy.Char8 as BL
17
18 -- To decode or encode a value using the generic machinery, we must
19 -- make the type an instance of the Generic class.
20
21 import GHC.Generics (Generic)
22
23 data Coord = Coord { x :: Double, y :: Double }
24 deriving (Show, Generic)
25
26 -- While we still have to declare our type as instances of FromJSON
27 -- and ToJSON, we do *not* need to provide bodies for the instances.
28 -- Default versions will be supplied for us.
29
30 instance FromJSON Coord
31 instance ToJSON Coord
32
33 main ::IO ()
34 main = do
35 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
36 print req
37 let reply = Coord 123.4 20
38 BL.putStrLn (encode reply)
Something went wrong with that request. Please try again.