我想将我的json转换为以下格式。并将以下格式转换为我的记录。请检查我在下面写的代码。
{
"uid" : "bob",
"emailid" : "bob@bob.com",
"email_verified" : "Y" // "Y" for EmailVerified and "N" for EmailNotVerified
}
我有以下代码,我试图将用户类型转换为json和从json转换用户类型 在Haskell中使用Aeson库
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
import Data.Monoid ((<>))
import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)
import Data.Aeson.Types
data User = User {
userId :: String,
userEmail :: String,
userEmailVerified :: EmailState
} deriving (Show, Generic)
data EmailState = EmailVerified | EmailNotVerified deriving (Generic, Show)
instance ToJSON User where
toJSON u = object [
"uid" .= userId u,
"emailid" .= userEmail u,
"email_verified" .= userEmailVerified u
]
instance FromJSON User where
parseJSON = withObject "User" $ \v -> User
<$> v .: "uid"
<*> v .: "emailid"
<*> v .: "email_verified"
instance ToJSON EmailState
instance FromJSON EmailState
但是,我目前能够生成的格式如下所示
{
"uid" : "bob",
"emailid" : "bob@bob.com",
"email_verified" : "EmailVerified"
}
答案 0 :(得分:4)
您需要自己实现ToJSON
EmailState
(因此请删除instance ToJSON EmailState
,并将其写为:)
instance ToJSON EmailState where
toJSON EmailVerified = String "Y"
toJSON EmailNotVerified = String "N"
您还需要更改解析器:
instance FromJSON EmailState where
parseJSON (String "Y") = return EmailVerified
parseJSON (String "N") = return EmailNotVerified
parseJSON _ = fail "Invalid JSON value to parse"
答案 1 :(得分:0)
威廉姆斯的令人敬畏的答案,只是为了添加语法 您可以使用-
instance FromJSON EmailState where
parseJSON (String s)
| s == "Y" = return EmailVerified
| s == "N" = return EmailNotVerified
| otherwise = fail "Invalid JSON value to parse"
-注意:否则= mzero-首选
ref:https://mail.haskell.org/pipermail/beginners/2011-October/008791.html