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
Run Code Online (Sandbox Code Playgroud)
我想要的是文字
test::User -> IO Text
test u = do
let j = pack ("{\"city\":\"test\",\"country\":\"test\",\"phone\":\"test\",\"email\":\"test\"}")
return j
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何从Value到Text
Nat*_*ell 13
这样做比我应该更加困难(我认为)是一个通常有用的功能.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
Run Code Online (Sandbox Code Playgroud)