0

我正在关注 Aeson库文档,但他们的示例似乎对我不起作用:

代码:

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

我在这里做错了吗?

4

1 回答 1

1

问题是decode期望 aByteString并且您正在传递 a String

试试这个ghci

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

在实际代码中,您不应该使用该Char8模块,因为它只是将Chars 截断为 8 位,而不考虑编码。通常,您应该从 a 开始ByteString,例如,使用 中的函数从磁盘读取它Data.ByteString.Lazy

于 2014-01-24T21:56:32.360 回答