on 1.1.0.0 help sign in
37 lines 1.1 kB history raw
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.
5-- We enable the DeriveGeneric language extension so that GHC can
6-- automatically derive the Generic class for us.
8{-# LANGUAGE DeriveGeneric #-}
9{-# LANGUAGE OverloadedStrings #-}
11module Main (main) where
13import Prelude ()
14import Prelude.Compat
16import Data.Aeson (FromJSON, ToJSON, decode, encode)
17import qualified Data.ByteString.Lazy.Char8 as BL
18import GHC.Generics (Generic)
20-- To decode or encode a value using the generic machinery, we must
21-- make the type an instance of the Generic class.
22data Coord = Coord { x :: Double, y :: Double }
23 deriving (Show, Generic)
25-- While we still have to declare our type as instances of FromJSON
26-- and ToJSON, we do *not* need to provide bodies for the instances.
27-- Default versions will be supplied for us.
29instance FromJSON Coord
30instance ToJSON Coord
32main :: IO ()
33main = do
34 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
35 print req
36 let reply = Coord { x = 123.4, y = 20 }
37 BL.putStrLn (encode reply)