10

我正在尝试用 aeson 解析以下 JSON。

{
    "data": [
        {
            "id": "34",
            "type": "link",
            "story": "foo"
        },
        {
            "id": "35",
            "type": "link",
            "story": "bar"
        }
    ]
}

由于我想忽略很多领域,看来我应该使用 GHC generics。但是如何编写使用 Haskell 关键字(如dataand )的数据类型定义type?以下当然给出:parse error on input `data'

data Feed = Feed {data :: [Post]}
    deriving (Show, Generic)

data Post = Post {
        id :: String,
        type :: String,
        story :: String
    }
    deriving (Show, Generic)
4

2 回答 2

13

您可以编写自己的FromJSON实例ToJSON而不依赖 GHC.Generics。这也意味着您可以为数据表示和 JSON 表示使用不同的字段名称。

Post 的示例实例:

{-# 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"

对于 Feed 也可以这样做。如果您不必忽略字段,您也可以使用deriveJSONfrom Data.Aeson.TH,它接受一个函数来修改字段名称作为它的第一个参数。

于 2013-08-23T20:07:50.983 回答
0

要将@bennofs 方法与通用方法结合起来,您可以按照Aeson 中的示例:教程

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Aeson
import Data.Aeson.Types

data Person = Person {
  _name :: String,
  _age  :: Int }
  deriving (Generic)

instance ToJSON Person where
  toJSON = genericToJSON defaultOptions {
             fieldLabelModifier = drop 1 }

instance FromJSON Person where
  parseJSON = genericParseJSON defaultOptions {
                fieldLabelModifier = drop 1 }

同时将 设置fieldLabelModifier为仅替换所需的标签:

keywordFieldLabelModifier "_id" = "id"
keywordFieldLabelModifier "_type" = "type"
keywordFieldLabelModifier = id
于 2021-01-05T11:11:28.813 回答