Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert constructor in record to custom json string in aeson haskell

I would like to convert my json to below format. And to convert from below format to my record. Please check the code that I have written below.

{
    "uid" : "bob",
    "emailid" : "[email protected]",
    "email_verified" : "Y" // "Y" for EmailVerified and "N" for EmailNotVerified
}

I have below code where I am trying to convert user type to and from json using Aeson library in Haskell

{-# 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

However, My format that I am currently able to generate is like below

{
    "uid" : "bob",
    "emailid" : "[email protected]",
    "email_verified" : "EmailVerified"
}
like image 765
navin Avatar asked Oct 18 '25 02:10

navin


1 Answers

You need to implement the ToJSON of EmailState yourself (so remove the instance ToJSON EmailState, and write it like):

instance ToJSON EmailState where
    toJSON EmailVerified = String "Y"
    toJSON EmailNotVerified = String "N"

You also will need to alter yhe parser:

instance FromJSON EmailState where
    parseJSON (String "Y") = return EmailVerified
    parseJSON (String "N") = return EmailNotVerified
    parseJSON _ = fail "Invalid JSON value to parse"
like image 137
Willem Van Onsem Avatar answered Oct 19 '25 19:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!