Created
May 19, 2012 17:24
-
-
Save krdlab/2731585 to your computer and use it in GitHub Desktop.
practice: Test Data.Aeson
This file contains hidden or 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 #-} | |
import qualified System.IO.UTF8 as U | |
import Control.Applicative ((<$>), (<*>)) | |
import Control.Monad (mzero) | |
import Data.Aeson | |
import Data.Aeson.Types | |
import Data.Text (Text) | |
import qualified Data.Attoparsec as AP (Result(..), parseOnly) | |
data Status = Status { text :: Text | |
, createdAt :: String | |
, user :: User | |
} deriving (Show) | |
data User = User { screenName :: String | |
} deriving (Show) | |
instance FromJSON Status where | |
parseJSON (Object v) = Status | |
<$> v .: "text" | |
<*> v .: "created_at" | |
<*> v .: "user" | |
parseJSON _ = mzero | |
instance FromJSON User where | |
parseJSON (Object v) = User | |
<$> v .: "screen_name" | |
parseJSON _ = mzero | |
main :: IO () | |
main = do | |
let p = AP.parseOnly json "{\"text\":\"ほげほげ\",\"created_at\":\"2012/05/20\",\"user\":{\"screen_name\":\"krdlab\"}}" | |
case p of | |
--Right j -> L.putStrLn $ encode j | |
Right j -> U.putStrLn $ show $ (fromJSON j :: Result Status) -- 日本語が化ける... | |
Left m -> U.putStrLn $ "parse error: " ++ m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment