2017-02-04 3 views
0
data ArticlePreview = ArticlePreview 
    { _articlePreviewName   :: T.Text 
    , _articlePreviewPerex   :: T.Text 
    , _articlePreviewAuthorName :: T.Text 
    , _articlePreviewAuthorUrl  :: T.Text 
    , _articlePreviewDate   :: T.Text 
    , _articlePreviewCategoryName :: T.Text 
    , _articlePreviewCategoryUrl :: T.Text 
    , _articlePreviewCommentsCount :: Maybe Integer 
    } deriving (Show, Eq, Generic) 

makeFields ''ArticlePreview 

J'ai essayé Aeson:Comment convertir automatiquement un enregistrement au format "makeFields" en format JSON avec des champs correspondant aux objectifs?

instance ToJSON ArticlePreview 
instance FromJSON ArticlePreview 

encodeToString :: ToJSON a => a -> String 
encodeToString = CL.unpack . encode 

Sorties:

{"_articlePreviewCommentsCount":17,"_articlePreviewAuthorName":"x","_articlePreviewName":"x","_articlePreviewCategoryName":"x","_articlePreviewAuthorUrl":"x","_articlePreviewCategoryUrl":"x","_articlePreviewDate":"x","_articlePreviewPerex":"x"} 

sortie souhaitée:

{"commentsCount":17,"authorName":"x","name":"x","categoryName":"x","authorUrl":"x","categoryUrl":"x","date":"x","perex":"x"} 

Je ne tiens pas Aeson, mais il doit être automatique (sans définition manuelle que, par exemple, _articlePreviewCommentsCount correspond à commentsCount).

Répondre

2

Vous pouvez obtenir FromJSON/ToJSON en utilisant le modèle Haskell de Data.Aeson.TH qui permet quelques modifications:

import Data.Aeson.TH 
import Data.Char 

deriveJSON 
    defaultOptions {fieldLabelModifier = (_head %~ toLower) . drop 15} 
    ''ArticlePreview 

t :: ArticlePreview 
t = ArticlePreview "" "" "" "" "" "" "" (Just 12) 

Ensuite, vous obtenez:

GHCI> encode t 
"{\"name\":\"\",\"perex\":\"\",\"authorName\":\"\",\"authorUrl\":\"\",\"date\":\"\",\"categoryName\":\"\",\"categoryUrl\":\"\",\"commentsCount\":12}" 
+0

Fonctionne très bien. Je n'étais pas sûr que ce serait possible. Je vous remercie :). – monnef