使用 aeson 为 json 中不可用的字段提供默认值

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

我正在尝试使用 Aeson 库加载 json。问题是我要加载它的数据结构包含的字段比 json.

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

json 中只有名称和文件字段可用。图片是光面图片所以无法真正从 json.

加载

我不知道如何省略 res 并从 FromJSON 实例中加载。

如果您不能从 JSON 加载该结构,那么就不要这样定义它!成功

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

可以从 JSON 轻松加载。然后你可以有一个额外的

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

...从未接触过 JSON。并实施

loadResource :: ResourceRef -> IO Resource