Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't Persistent types instances of ToJSON/FromJSON in Yesod?

It's not that hard to write ToJSON/FromJSON instances for the generated types but still, while you're generating code could you throw that in? Or is there an easy way to make this happen as a Yesod user? (I haven't dug too deep into how TH works...)

Update: OK, I like this suggestion but, say my persistent type is User. If I use

$(deriveJSON id ''User)

it yields

  Exception when trying to run compile-time code:
  Data.Aeson.TH.withType: Unsupported type: TySynD Model.User [] (AppT (ConT Model.UserGeneric) (ConT Database.Persist.GenericSql.Raw.SqlPersist))
  Code: deriveJSON (id) 'User

apparently because it's an alias. But

$(deriveJSON id ''UserGeneric)

yields

Kind mis-match
The first argument of `UserGeneric' should have kind `(* -> *)
                                                      -> *
                                                      -> *',
but `backend[i5XB]' has kind `*'

I've probably still got the wrong type but I can't find enough about what Persistent generates to get the right incantation.

like image 733
svachalek Avatar asked Feb 02 '12 01:02

svachalek


3 Answers

For anyone who doesn't notice the sub comment on Michael Snowman's post, in resent versions of persistent you can do:

Person json
    name Text
    age Int

and get ToJSON and FromJSON instances of Person.

like image 69
triplepoint217 Avatar answered Nov 12 '22 23:11

triplepoint217


I actually think we'll be adding this feature to Persistent 0.8 (to be released with Yesod 0.10 in a week or two). It's true what dflemstr said about dependency bloat, which is why we haven't done this in the past, but we already depend on aeson now for our configuration types (based on Yaml config files, which uses aeson's data types).

like image 29
Michael Snoyman Avatar answered Nov 12 '22 23:11

Michael Snoyman


You can just use the automatic deriving mechanism in Data.Aeson.TH.

{-# LANGUAGE TemplateHaskell #-}
$(deriveJSON id ''Foo)

This should work fine on both Yesod-generated data types as well as your own types.

It takes a function to customize the record field names. Here, I've just passed id to get them unchanged. See the documentation for details.

like image 39
hammar Avatar answered Nov 12 '22 21:11

hammar