Допустим, есть тип данных с опциональным полем:
data Test = Test Int (Maybe String)
deriving (Eq, Read, Show)
instance FromJSON Test where
parseJSON (Object o) = do
n ← o .: "int"
s ← o .:? "str"
return $ Test n s
parseJSON _ = empty
instance ToJSON Test where
toJSON (Test n s) = object
[ "int" .= n
, "str" .= s
]
> encode $ Test 1 Nothing
Chunk "{\"str\":null,\"int\":1}" Empty
it :: BSC.ByteString
> encode $ Test 1 Nothing
Chunk "{\"int\":1}" Empty
it :: BSC.ByteString
Ну и да, ответы вида
instance ToJSON Test where
toJSON (Test n (Just s)) = object
[ "int" .= n
, "str" .= s
]
toJSON (Test n Nothing) = object
[ "int" .= n
]