Skip to content

Instantly share code, notes, and snippets.

@scudelletti
Last active March 16, 2021 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scudelletti/6c740b1596269940e51be0a23516aee6 to your computer and use it in GitHub Desktop.
Save scudelletti/6c740b1596269940e51be0a23516aee6 to your computer and use it in GitHub Desktop.
Encode/Decode Sum Types manually using Aeson (Haskell) - No Generic
{-# LANGUAGE OverloadedStrings #-}
module Stuff where
import Data.Aeson
import Data.ByteString.Lazy.Char8 as BC
data FooBar = Foo | Bar deriving (Eq, Show)
instance ToJSON FooBar where
toJSON Foo = String "Fu"
toJSON Bar = String "Baz"
instance FromJSON FooBar where
parseJSON (String "Fu") = pure Foo
parseJSON (String "Baz") = pure Bar
parseJSON invalid = fail "Unable to parse"
-- Returns "\"Fu\""
fooJSON :: BC.ByteString
fooJSON = encode Foo
-- Returns "\"Baz\""
barJSON :: BC.ByteString
barJSON = encode Bar
-- Returns Foo
fooFromJSON :: Maybe FooBar
fooFromJSON = decode "\"Fu\""
-- Returns Bar
barFromJSON :: Maybe FooBar
barFromJSON = decode "\"Baz\""
-- Returns Nothing
invalidFromWrongJSON :: Maybe FooBar
invalidFromWrongJSON = decode "Boom"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment