on weeder-instances help sign in
41 lines 1.0 kB history raw
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE RecordWildCards #-}
4module Main (main) where
6import Prelude ()
7import Prelude.Compat
9import Control.Applicative (empty)
10import Data.Aeson
11import Data.Monoid
12import qualified Data.ByteString.Lazy.Char8 as BL
14data Coord = Coord { x :: Double, y :: Double }
15 deriving (Show)
17-- A ToJSON instance allows us to encode a value as JSON.
19instance ToJSON Coord where
20 toJSON (Coord xV yV) = object [ "x" .= xV,
21 "y" .= yV ]
23 toEncoding Coord{..} = pairs $
24 "x" .= x <>
25 "y" .= y
27-- A FromJSON instance allows us to decode a value from JSON. This
28-- should match the format used by the ToJSON instance.
30instance FromJSON Coord where
31 parseJSON (Object v) = Coord <$>
32 v .: "x" <*>
33 v .: "y"
34 parseJSON _ = empty
36main :: IO ()
37main = do
38 let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
39 print req
40 let reply = Coord 123.4 20
41 BL.putStrLn (encode reply)