Created
March 5, 2016 21:21
-
-
Save merryhime/446ca32840187011bbf0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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