来自JSON实例的Aeson

时间:2011-09-02 00:32:31

标签: json haskell

我有以下数据类型:

 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  }

以下实例:

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 .: "email" <*> o .: "password"
    parseJSON _          = mzero

但是用户被分成两部分,因为有时在couchdb中的文档没有像secret或password这样的字段。 我怎样才能为数据类型创建一个fromJSON实例:

   data User = User { name :: T.Text, bookCount :: Int ,memberSince :: DateTime ,
      email :: T.Text, password :: B.ByteString , secret :: Integer  }

哪些字段是强制性的而其他字段不是?

1 个答案:

答案 0 :(得分:4)

为什么不使用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"