Skip to content

Instantly share code, notes, and snippets.

@merryhime
Created March 5, 2016 21:21
Show Gist options
  • Save merryhime/446ca32840187011bbf0 to your computer and use it in GitHub Desktop.
Save merryhime/446ca32840187011bbf0 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson
import qualified Data.Aeson.Types as T
import Data.Text (Text)
import Control.Applicative ((<$>))
import Control.Monad (mzero)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
data Msg = Msg Color deriving (Show)
data Color = Red | Blue | Green deriving (Show)
instance FromJSON Color where
parseJSON (String "green") = return $ Green
parseJSON (String "red") = return $ Red
parseJSON (String "blue") = return $ Blue
parseJSON _ = mzero
instance FromJSON Msg where
parseJSON (Object v) = Msg <$> v .: "color"
parseJSON _ = mzero
parseMsgFromString :: String -> Maybe Msg
parseMsgFromString s = let bs = BSL.pack s
in decode bs
exampleJSONMessage :: String
exampleJSONMessage = "{\"color\":\"blue\"}"
main ::IO ()
main = do
print $ parseMsgFromString exampleJSONMessage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment