aeson icon indicating copy to clipboard operation
aeson copied to clipboard

Add default wrapper

Open treeowl opened this issue 6 years ago • 5 comments
trafficstars

newtype DefaultJSON a = DefaultJSON a

instance (Generic a, GToJSON Zero (Rep a), GToEncoding Zero (Rep a))
    => ToJSON (DefaultJSON a) where
  toJSON (DefaultJSON a) = genericToJSON defaultOptions a
  toEncoding (DefaultJSON a) = genericToEncoding defaultOptions a

instance (Generic a, GFromJSON Zero (Rep a)) => FromJSON (DefaultJSON a) where
  parseJSON x = DefaultJSON <$> genericParseJSON defaultOptions x

This can be used with DerivingVia:

data Message val = Message {val :: val, teamId :: Int, messageType :: Char}
  deriving Generic
  deriving (ToJSON, FromJSON) via DefaultJSON (Message val)

This is almost as easy as writing empty instances, but it includes the toEncoding optimization for ToJSON.

treeowl avatar Aug 19 '19 10:08 treeowl

Looks nice 👍

bergmark avatar Aug 19 '19 15:08 bergmark

There's an active proposal (by Alexis King) to add Generically to base. We might be better off waiting to see if that happens, and use it if so.

treeowl avatar Sep 04 '19 19:09 treeowl

Looks like Generically isn't happening. I'll add something to aeson in meanwhile.

phadej avatar Mar 06 '21 16:03 phadej

@bergmark What you think, what would be better module name to include this (and e.g. DotNetTime and others types).

  • Data.Aeson.Deriving
  • Data.Aeson.Newtypes

or something else?

phadej avatar Mar 07 '21 11:03 phadej

I like .Deriving for this one and other helpers. For DotNetTime and friends I'd like a name that reflects the use case, not how they are implemented (shouldn't matter if DotNetTime is derived, a newtype, or written manually). Data.Aeson.Types is taken :-S Data.Aeson.Data might be too generic.Data.Aeson.JSONTypes (also generic... edit: and misleading, these are not defined in the json spec)?

bergmark avatar Mar 07 '21 11:03 bergmark

I think this can be closed as an instance as suggested above was added for Generically in #951 and released in 2.1.0.0.

amesgen avatar Apr 11 '23 21:04 amesgen