Aeson示例不起作用

时间:2014-01-24 21:50:00

标签: haskell aeson

我正在关注Aeson library documentation,但他们的例子似乎对我不起作用:

代码:

 {-# LANGUAGE OverloadedStrings #-}

import Data.Text
import Data.Aeson
import Control.Applicative ((<$>),(<*>))
import Control.Monad

instance FromJSON Person where
  parseJSON (Object v) = Person <$>
                         v .: "name" <*>
                         v .: "age"
  -- A non-Object value is of the wrong type, so fail.
  parseJSON _          = mzero

data Person = Person
              { name :: Text
              , age  :: Int
              } deriving Show

错误报告:

ghci> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString'
            with actual type `[Char]'
In the first argument of `decode', namely
  `"{\"name\":\"Joe\",\"age\":12}"'
In the expression:
    decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
In an equation for `a':
    a = decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

问题是,decode需要ByteString,而您传递String

ghci

中试试
:m +Data.ByteString.Lazy.Char8
decode $ pack "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

在实际代码中,您不应该使用Char8模块,因为它只会将Char s截断为8位而不考虑编码。一般来说,您的目标应该是ByteString,例如通过使用Data.ByteString.Lazy中的函数从磁盘读取它。