Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically deriving toJSON/fromJSON using the instances of the inner type of a newtype

Tags:

haskell

aeson

In my code I use a lot of newtype declarations, like:

newtype PersonName = PersonName { personName :: Text }
newtype PetName = PetName { petName :: Text }

(In practice I use lenses to avoid the cumbersome names for the accessor functions.)

However, if I derive the instance from ToJSON and FromJSON automatically, the resulting JSON will be of the form:

{ "personName": "The person name" }
{ "petName": "The pet name" }

Is there a way to avoid the boilerplate of declaring trivial instances of ToJSON and FromJSON for the newtypes above, in such a way that the resulting JSON objects will be of the form:

"The person name"
"The pet name"
like image 631
Damian Nadales Avatar asked Sep 01 '25 22:09

Damian Nadales


1 Answers

You can use GeneralizedNewtypeDeriving to derive the instances.

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype PersonName = PersonName { personName :: Text }
    deriving (ToJSON, FromJSON)
like image 195
luqui Avatar answered Sep 05 '25 17:09

luqui