Last active
March 16, 2021 08:40
-
-
Save scudelletti/6c740b1596269940e51be0a23516aee6 to your computer and use it in GitHub Desktop.
Encode/Decode Sum Types manually using Aeson (Haskell) - No Generic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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