7
data User = User { city :: Text
                 , country :: Text
                 , phone :: Text
                 , email :: Text}

instance ToJSON User where
    toJSON (User a b c d)= object ["a" .= a
                                  ,"b" .= b
                                  ,"c" .= c
                                  ,"d" .= d]

test:: User -> IO Value
test u = do
    let j = toJSON u
    return j

我想要的是这样的文本

test::User -> IO Text
test u = do
    let j = pack ("{\"city\":\"test\",\"country\":\"test\",\"phone\":\"test\",\"email\":\"test\"}")
    return j

我不知道如何从值到文本

4

2 回答 2

14

对于(我认为)通常有用的功能来说,这样做比应该做的更难。Data.Aeson.Encode.encode做了太多的工作并将其一直转换为ByteString.

从转换开始encode并切换Lazy.Text -> ByteStringLazy.Text -> Strict.Text转换可以满足您的要求:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Aeson.Encode (fromValue)
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)

data User = User
  { city    :: Text
  , country :: Text
  , phone   :: Text
  , email   :: Text
  }

instance ToJSON User where
  toJSON (User a b c d) = object
    [ "city"    .= a
    , "country" .= b
    , "phone"   .= c
    , "email"   .= d
    ]

test :: User -> Text
test = toStrict . toLazyText . encodeToTextBuilder . toJSON
于 2012-08-16T18:57:56.533 回答
1

根据 Thomas 的评论:您不是从Valueto Text,而是从Valueto ByteString。该sendTextData函数是多态的,足以接受ByteStrings。

于 2012-08-17T10:06:16.433 回答