如何自动转换“中的记录”;makeFields“;镜头格式转换为JSON,字段匹配镜头?
我试过埃森:如何自动转换“中的记录”;makeFields“;镜头格式转换为JSON,字段匹配镜头?,json,haskell,record,haskell-lens,Json,Haskell,Record,Haskell Lens,我试过埃森: data ArticlePreview = ArticlePreview { _articlePreviewName :: T.Text , _articlePreviewPerex :: T.Text , _articlePreviewAuthorName :: T.Text , _articlePreviewAuthorUrl :: T.Text , _articlePreviewDate :
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
产出:
instance ToJSON ArticlePreview
instance FromJSON ArticlePreview
encodeToString :: ToJSON a => a -> String
encodeToString = CL.unpack . encode
期望输出:
{"_articlePreviewCommentsCount":17,"_articlePreviewAuthorName":"x","_articlePreviewName":"x","_articlePreviewCategoryName":"x","_articlePreviewAuthorUrl":"x","_articlePreviewCategoryUrl":"x","_articlePreviewDate":"x","_articlePreviewPerex":"x"}
我不坚持Aeson,但它必须是自动的(没有手动定义,例如,
\u articlePreviewCommentScont
映射到CommentScont
)。您可以使用模板Haskell从JSON/到JSON
,该模板允许进行一些修改:
{"commentsCount":17,"authorName":"x","name":"x","categoryName":"x","authorUrl":"x","categoryUrl":"x","date":"x","perex":"x"}
然后你会得到:
import Data.Aeson.TH
import Data.Char
deriveJSON
defaultOptions {fieldLabelModifier = (_head %~ toLower) . drop 15}
''ArticlePreview
t :: ArticlePreview
t = ArticlePreview "" "" "" "" "" "" "" (Just 12)
您可以使用模板Haskell从JSON/
到JSON
派生,该模板允许进行一些修改:
{"commentsCount":17,"authorName":"x","name":"x","categoryName":"x","authorUrl":"x","categoryUrl":"x","date":"x","perex":"x"}
然后你会得到:
import Data.Aeson.TH
import Data.Char
deriveJSON
defaultOptions {fieldLabelModifier = (_head %~ toLower) . drop 15}
''ArticlePreview
t :: ArticlePreview
t = ArticlePreview "" "" "" "" "" "" "" (Just 12)
效果很好。我不确定这是否可能。谢谢:)。效果很好。我不确定这是否可能。谢谢:)。