Aeson fromJSON instance
I have the following data type:
data User = User { name :: T.Text, bookCount :: Int ,memberSince :: DateTime ,
email :: T.Text, password :: B.ByteString }
| UnverifiedUser { nameUnverified :: T.Text, emailUnverified :: T.Text,
secret :: Integer }
And the following instance:
instance FromJSON User where
parseJSON (Object o) | Just _ <- M.lookup "secret" o = UnverifiedUser <$> o .: "name" <*> o .: "email" <*> o .: "secret"
| otherwise = User <$> o .: "name" <*> o .: "bookCount" <*> o .: "memberSince" <*> o .: "e开发者_如何学Pythonmail" <*> o .: "password"
parseJSON _ = mzero
But User was split into two, because sometimes the document in couchdb does not have some fields like secret, or password. How could I make an fromJSON instance for the data type:
data User = User { name :: T.Text, bookCount :: Int ,memberSince :: DateTime ,
email :: T.Text, password :: B.ByteString , secret :: Integer }
where some fields are mandatory and others are not ?
Why not use Maybe
?
data User =
User {
name :: T.Text,
bookCount :: Int ,
memberSince :: DateTime ,
email :: T.Text,
password :: Maybe B.ByteString,
nameUnverified :: T.Text,
emailUnverified :: T.Text,
secret :: Maybe Integer}
instance FromJSON User where
parseJSON (Object o) = User <$>
o .: "name" <*>
o .: "bookCount" <*>
o .: "memberSince" <*>
o .: "email" <*>
o .:? "password" <*>
o .: "nameUnverified" <*>
o .: "emailUnverified" <*>
o .:? "secret"
精彩评论