aeson是haskell的一个库,其实我也不太懂,不过大概是这样的:
定义一个类型
如
data Person =
Person { firstName :: String
, lastName :: String
, age :: Int
, likesPizza :: Bool
} deriving Show
然后我们来实现FromJSON , ToJSON这两个class
instance FromJSON Person where
parseJSON (Object v) =
Person <$> v .: "firstName"
<*> v .: "lastName"
<*> v .: "age"
<*> v .: "likesPizza"
parseJSON _ = mzero instance ToJSON Person where
toJSON (Person firstName lastName age likesPizza) =
object [ "firstName" .= firstName
, "lastName" .= lastName
, "age" .= age
, "likesPizza" .= likesPizza
]
不过呢,也不用都这么写,打开ghc的DeriveGeneric扩展,就可以让编译器帮我们自动生成了
data Person =
Person { firstName :: String
, lastName :: String
, age :: Int
, likesPizza :: Bool
} deriving (Show , Generic) instance FromJSON Person
instance ToJSON Person
就这么简单!
处理JSON为两个,encode和decode
decode :: FromJSON a => ByteString -> Maybe a
encode :: ToJSON a => a -> ByteString
下面是一个完整的读取acmicpc.info提供的比赛的JSON的代码
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} import Data.Aeson
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Lazy as B
import Network.HTTP.Conduit (simpleHttp)
import Network.Socket (withSocketsDo) import Data.Map
import GHC.Generics
data Contest =
Contest{
id :: String ,
oj :: String ,
link :: String ,
name :: String ,
start_time :: String ,
week :: String ,
access :: String
} deriving (Show , Generic) instance FromJSON Contest
instance ToJSON Contest jsonURL :: String
jsonURL = "http://contests.acmicpc.info/contests.json" getJSON :: IO B.ByteString
getJSON = withSocketsDo $ simpleHttp jsonURL main :: IO ()
main = do
d <- (eitherDecode <$> getJSON) :: IO (Either String [Contest])
case d of
Left err -> putStrLn err
Right ps -> print ps
- -基本都是抄的例子,不过要主意的是simpleHttp在windows下面要在前面加个withSocketsDo...不然会有一个10093的错误,说file not exists
getAddrInfo: does not exist (error 10093)