我试图用aeson解析下面的
JSON.
{ "data": [ { "id": "34","type": "link","story": "foo" },{ "id": "35","story": "bar" } ] }
既然有很多字段我想忽略,似乎是I should use GHC generics.但是如何编写使用Haskell关键字(如数据和类型)的数据类型定义?以下当然给出:输入`data’的解析错误
data Feed = Feed {data :: [Post]} deriving (Show,Generic) data Post = Post { id :: String,type :: String,story :: String } deriving (Show,Generic)
解决方法
您可以编写自己的FromJSON和ToJSON实例,而不依赖于GHC.Generics.这也意味着您可以为数据表示和JSON表示使用不同的字段名称.
帖子示例:
{-# LANGUAGE OverloadedStrings #-} import Control.Applicative import Data.Aeson import qualified Data.ByteString.Lazy as LBS data Post = Post { postId :: String,typ :: String,story :: String } deriving (Show) instance FromJSON Post where parseJSON (Object x) = Post <$> x .: "id" <*> x.: "type" <*> x .: "story" parseJSON _ = fail "Expected an Object" instance ToJSON Post where toJSON post = object [ "id" .= postId post,"type" .= typ post,"story" .= story post ] main :: IO () main = do print $(decode $Post "{\"type\": \"myType\",\"story\": \"Really interresting story\",\"id\" : \"SomeId\"}" :: Maybe Post) LBS.putStrLn $encode $Post "myId" "myType" "Some other story"
饲料可以做同样的事情.如果不必忽略字段,那么也可以使用来自Data.Aeson.TH的derivedJSON,它可以修改字段名称作为第一个参数.