Give a default value for fields not available in json using aeson

一个人想着一个人 提交于 2019-12-14 04:11:39

问题


I am trying to load json using the Aeson library. The thing is that the datastructure that I want to load it into contains more fields than the json.

data Resource = Res {
                  name :: String,
                  file :: FilePath,
                  res :: Picture,
                  loaded :: Bool
                } deriving (Generic, Show)

Where only the name and the file fields are available in the json. Picture is a gloss Picture so that can't really be loaded from json.

I can't figure out how to leave out res and loaded out of the FromJSON instance.


回答1:


If you can't load that structure from JSON, then don't define it this way! Make it

data ResourceRef = ResRef
                { name :: String
                , file :: FilePath
                } deriving (Generic, Show)

That can be easily loaded from JSON. You can then have an additional

data Resource = Res
                { resName :: String
                , resFile :: FilePath
                , res :: Picture
                } deriving (Generic, Show)

...which never gets in contact with JSON. And implement

loadResource :: ResourceRef -> IO Resource


来源:https://stackoverflow.com/questions/46810998/give-a-default-value-for-fields-not-available-in-json-using-aeson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!