Why aren't ToJSON / FromJSON instance types repeated in Yesod?

It is not so difficult to write ToJSON / FromJSON instances for the generated types, but still, while you are generating the code, can you insert it? Or is there an easy way to do this as a Yesod user? (I'm not too deep into how TH works ...)

Update: Well, I like this sentence, but let's say my constant type is User. If i use

$(deriveJSON id ''User) 

He gives

  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 

obviously because it is a pseudonym. But

 $(deriveJSON id ''UserGeneric) 

gives

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

I probably still have the wrong type, but I can't find enough of what Persistent generates to get the right spell.

+6
source share
4 answers

I really think we will add this feature to Persistent 0.8 (coming out with Yesod 0.10 in a week or two). It is true that dflemstr said dependencies were hanging, so we haven’t done this before, but now we are already dependent on aeson for our configuration types (based on Yaml configuration files that use aeson data types).

+5
source

For those who do not notice an additional 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.

+8
source

You can simply use the automatic output mechanism in Data.Aeson.TH .

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

This should work fine for both the data types generated by Yesod and your own types.

A function is required to configure the names of the fields in a record. Here I just went through the id so they don't change. See the documentation for more details .

+2
source

Yesod generator generators by default should not generate ToJSON / FromJSON , because this will add aeson , even if you do not want to use this package, which can lead to dependency hangs.

You can import Data.Aeson.TH and use this code to automatically create JSON instances:

 data MyDataType = ... deriveJSON id ''MyDataType 

Replace id with a function that renames fields for you if you do not want the same field names in Haskell as in the JSON file.

+1
source

Source: https://habr.com/ru/post/907449/


All Articles