You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
(What is tidy is in the eye of the beholder, but I believe: {"attach":{"tel":"+447890"}} is tidier than {"tag":"AttachMsg","contents":{"tel":"+447890"}}.)
I've spent some time playing around with Aeson, but I can't get Algebraic Data Types to serialise nicely.
What I've tried is:
data Attach = Attach { tel :: String }
deriving (Show)
$(deriveJSON defaultOptions ''Attach)
data Fix = Fix { lat :: Double, lng :: Double }
deriving (Show)
$(deriveJSON defaultOptions ''Fix)
data MsgIn = AttachMsg Attach
| FixMsg Fix
deriving (Show)
$(deriveJSON defaultOptions ''MsgIn)
data MsgIn2 = MsgIn2 { attach :: Maybe Attach, fix :: Maybe Fix }
deriving (Show)
$(deriveJSON defaultOptions ''MsgIn2)
someFunc :: IO ()
someFunc = do
let attach = Attach "+447890"
let reply = AttachMsg attach
BL.putStrLn (encode reply)
let reply2 = MsgIn2 (Just attach) Nothing
BL.putStrLn (encode reply2)
Use custom options instead of defaultOptions. You can get the right structure by using sumEncoding = ObjectWithSingleField, which reduces your first example to {"AttachMsg":{"tel":"+447890"}}. You can then customize the constructor tags by using constructorTagModifier = myConstructorTag and by writing a function myConstructorTag that customizes the names to your liking (e.g. AttachMsg -> attach).
As an example, you'll get the output you want by writing this into a separate module, importing it, and using myOptions instead of defaultOptions:
A separate module is needed here because of Template Haskell. There's probably a way to define myConstructorTag and myOptions in a better way to satisfy the needs of TH, but I have absolutely no idea how to do that.
Crossposted: http://stackoverflow.com/questions/31439991/how-to-write-haskell-adts-as-tidy-json-using-aeson
(What is tidy is in the eye of the beholder, but I believe:
{"attach":{"tel":"+447890"}}
is tidier than{"tag":"AttachMsg","contents":{"tel":"+447890"}}
.)I've spent some time playing around with Aeson, but I can't get Algebraic Data Types to serialise nicely.
What I've tried is:
The output is:
The output I'm looking for is:
but from the
MsgIn
type, rather thanMsgIn2
.(The output of
MsgIn2
gets quite close, but it's got an explicitnull
.)Is there a way of doing this in Aeson?
The text was updated successfully, but these errors were encountered: