将记录中的构造函数转换为 aeson haskell 中的自定义 json 字符串

Convert constructor in record to custom json string in aeson haskell

我想将我的 json 转换为以下格式。并从以下格式转换为我的记录。请检查我在下面编写的代码。

{
    "uid" : "bob",
    "emailid" : "bob@bob.com",
    "email_verified" : "Y" // "Y" for EmailVerified and "N" for EmailNotVerified
}

我在下面的代码中尝试将用户类型与 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"
}

你需要自己实现EmailStateToJSON(所以去掉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"

Willem 的精彩回答,只是为了添加语法 你可以使用 -

instance FromJSON EmailState where
    parseJSON (String s) 
        | s == "Y" = return EmailVerified
        | s == "N" = return EmailNotVerified
        | otherwise = fail "Invalid JSON value to parse"

-- 注意:otherwise = mzero -- 优先

参考:https://mail.haskell.org/pipermail/beginners/2011-October/008791.html