@@ -16,14 +16,18 @@
1616
1717module Data.Aeson.Generic
1818 (
19− fromJSON
19+ -- * Decoding and encoding
20+ decode
21+ , encode
22+ -- * Lower-level conversion functions
23+ , fromJSON
2024 , toJSON
2125 ) where
2226
2327import Control.Applicative ((<$>))
2428import Control.Arrow (first)
2529import Control.Monad.State.Strict
26−import Data.Aeson.Functions
30+import Data.Aeson.Functions hiding (decode)
2731import Data.Aeson.Types hiding (FromJSON(..), ToJSON(..), fromJSON)
2832import Data.Attoparsec.Number (Number)
2933import Data.Generics
@@ -35,7 +39,11 @@ import Data.Text (Text, pack, unpack)
3539import Data.Text.Encoding (encodeUtf8)
3640import Data.Time.Clock (UTCTime)
3741import Data.Word (Word, Word8, Word16, Word32, Word64)
42+import Data.Aeson.Parser (json)
43+import qualified Data.Aeson.Encode as E
44+import qualified Data.Aeson.Functions as F
3845import qualified Data.Aeson.Types as T
46+import qualified Data.Attoparsec.Lazy as L
3947import qualified Data.ByteString as B
4048import qualified Data.ByteString.Lazy as L
4149import qualified Data.HashMap.Strict as H
@@ -46,6 +54,21 @@ import qualified Data.Text.Lazy as LT
4654import qualified Data.Traversable as T
4755import qualified Data.Vector as V
4856
57+-- | Efficiently serialize a JSON value as a lazy 'L.ByteString'.
58+encode :: (Data a) => a -> L.ByteString
59+encode = E.encode . toJSON
60+{-# INLINE encode #-}
61+
62+-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
63+-- If this fails due to incomplete or invalid input, 'Nothing' is
64+-- returned.
65+decode :: (Data a) => L.ByteString -> Maybe a
66+decode s = case L.parse json s of
67+ L.Done _ v -> case fromJSON v of
68+ Success a -> Just a
69+ _ -> Nothing
70+ _ -> Nothing
71+
4972type T a = a -> Value
5073
5174toJSON :: (Data a) => a -> Value
@@ -93,7 +116,7 @@ toJSON = toJSON_generic
93116 | tyrep == typeOf DT.empty = remap id
94117 | tyrep == typeOf LT.empty = remap LT.toStrict
95118 | tyrep == typeOf "" = remap pack
96− | tyrep == typeOf B.empty = remap decode
119+ | tyrep == typeOf B.empty = remap F.decode
97120 | tyrep == typeOf L.empty = remap strict
98121 | otherwise = modError "toJSON" $
99122 "cannot convert map keyed by type " ++ show tyrep
@@ -104,7 +127,7 @@ toJSON = toJSON_generic
104127 | tyrep == typeOf DT.empty = remap id
105128 | tyrep == typeOf LT.empty = remap LT.toStrict
106129 | tyrep == typeOf "" = remap pack
107− | tyrep == typeOf B.empty = remap decode
130+ | tyrep == typeOf B.empty = remap F.decode
108131 | tyrep == typeOf L.empty = remap strict
109132 | otherwise = modError "toJSON" $
110133 "cannot convert map keyed by type " ++ show tyrep