on master help sign in
Encode the constructors of Either so that "fromJSON . toJSON == id" holds
commit3cc7cd00412169447bcdaba4a3f334db07caa235 authorBas van Dijk <v.dijk.bas@gmail.com> dateFri 8 Jul 2011, 16:36 (15 years ago) parent00a185a
1 file changed+12−4
Data/Aeson/Types.hs+12−4
Data/Aeson/Types.hs+12−4
@@ -1,5 +1,6 @@
11{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, GeneralizedNewtypeDeriving,
2− IncoherentInstances, OverlappingInstances, OverloadedStrings, Rank2Types #-}
2+ IncoherentInstances, OverlappingInstances, OverloadedStrings, Rank2Types,
3+ ViewPatterns #-}
34
45-- |
56-- Module: Data.Aeson.Types
@@ -325,14 +326,21 @@ instance (FromJSON a) => FromJSON (Maybe a) where
325326 {-# INLINE parseJSON #-}
326327
327328instance (ToJSON a, ToJSON b) => ToJSON (Either a b) where
328− toJSON (Left a) = toJSON a
329− toJSON (Right b) = toJSON b
329+ toJSON (Left a) = object [left .= a]
330+ toJSON (Right b) = object [right .= b]
330331 {-# INLINE toJSON #-}
331332
332333instance (FromJSON a, FromJSON b) => FromJSON (Either a b) where
333− parseJSON a = Left <$> parseJSON a <|> Right <$> parseJSON a
334+ parseJSON (Object (M.toList -> [(key, value)]))
335+ | key == left = Left <$> parseJSON value
336+ | key == right = Right <$> parseJSON value
337+ parseJSON _ = mzero
334338 {-# INLINE parseJSON #-}
335339
340+left, right :: Text
341+left = "Left"
342+right = "Right"
343+
336344instance ToJSON Bool where
337345 toJSON = Bool
338346 {-# INLINE toJSON #-}