json - Override how Data.Aeson handles only one field of my record -
i making rest api university courses:
data course of study = course of study { id :: maybe text, name :: text, deleted :: bool } deriving(show, generic) instance fromjson course of study instance tojson course of study
i allow deleted
optional in serialized json structure, not in application. want set deleted
false
if isn't specified when parsing.
i write manual instance fromjson
, don't want have write out fields. want declare how deleted handled , allow automatic instance handle else.
how this?
to knowledge there not way customize generic instance, construction type bit differently:
data course of study = course of study { courseid :: maybe text -- don't utilize `id`, it's function , name :: text } deriving (show, generic) info deletable = deletable { deleted :: bool , item :: } deriving (show) instance fromjson course of study instance tojson course of study instance fromjson => fromjson (deletable a) parsejson (object v) = <- parsejson (object v) d <- v .:? "deleted" .!= false homecoming $ deletable d parsejson _ = mzero
now can do
> allow nodeleted = "{\"name\":\"math\",\"courseid\":\"12345\"}" :: text > allow withdeleted = "{\"name\":\"math\",\"courseid\":\"12345\",\"deleted\":true}" :: text > decode nodeleted :: maybe (deletable course) (deletable {deleted = false, item = course of study {courseid = "12345", name = "math"}}) > decode nodeleted :: maybe course of study (course {courseid = "12345", name = "math"}) > decode withdeleted :: maybe (deletable course) (deletable {deleted = true, item = course of study {courseid = "12345", name = "math"}}) > decode withdeleted :: maybe course of study (course {courseid = "12345", name = "math"})
and can optionally tag course of study deletable when need it, , fromjson
instances take care of everything.
json haskell aeson
No comments:
Post a Comment