J'ai passé du temps à jouer avec Aeson, mais je n'arrive pas à obtenir des types de données algébriques pour sérialiser correctement.Comment sérialiser les ADT Haskell en tant que JSON ordonné, en utilisant Aeson?
Ce que j'ai essayé est:
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)
La sortie est:
{"tag":"AttachMsg","contents":{"tel":"+447890"}}
{"attach":{"tel":"+447890"},"fix":null}
La sortie Je cherche est:
{"attach":{"tel":"+447890"}}
mais à partir du type MsgIn
plutôt que MsgIn2
.
(La sortie de MsgIn2
obtient assez proche, mais il a une null
explicite.)
Est-il possible de le faire en Aeson?
Mise à jour:
J'ajouté:
instance ToJSON MsgIn3 where
toJSON (AttachMsg3 (Attach tel)) = object ["attach" .= object ["tel" .= tel]]
...
let reply3 = AttachMsg3 attach
BL.putStrLn (encode reply3)
et a obtenu la réponse que je voulais: {"attach":{"tel":"+447890"}}
.
@bheklilr existe-t-il un moyen d'utiliser la sérialisation de Attach (déjà définie) au lieu de la définir à nouveau?
J'ai essayé une syntaxe non-sens, mais compréhensible, il ne compile pas:
instance ToJSON MsgIn3 where
toJSON (AttachMsg3 (Attach tel)) = object ["attach" .= (toJSON :: Attach)]
Vous pouvez simplement écrire les instances 'ToJSON' et' FromJSON' manuellement pour obtenir exactement ce que vous voulez: 'toJSON (AttachMsg (Attach tel)) = objet [" attacher ". = Objet [" tel ". = Tel] ] ', et de même pour' FixMsg'. L'implémentation 'parseJSON' ne serait pas beaucoup plus difficile. – bheklilr
@bheklilr Merci, c'était vraiment utile. Pourriez-vous en faire une réponse?Pourriez-vous voir ma question mise à jour ... – fadedbee