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
我无法弄清楚如何从价值转向文本
答案 0 :(得分:12)
这样做比应该更加困难(我认为)是一个通常有用的功能。 Data.Aeson.Encode.encode
做了太多工作,并将其一直转换为ByteString
。
从encode
开始并将Lazy.Text -> ByteString
切换为Lazy.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
答案 1 :(得分:1)
Per Thomas的评论:您不是从Value
转到Text
,而是从Value
转到ByteString
。 sendTextData
函数的多态性足以接受ByteString
s。