使用aeson为json中不可用的字段提供默认值 [英] Give a default value for fields not available in json using aeson

查看:293
本文介绍了使用aeson为json中不可用的字段提供默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Aeson库加载json。问题是我想加载到的数据结构包含比json更多的字段。

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)

其中只有名称和文件字段在json中可用。图片是一张光泽图片,因此无法真正从json加载。

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.

我无法弄清楚如何省略res并将其加载出FromJSON实例。

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

推荐答案

如果您无法从JSON加载该结构,那么请不要这样定义它!使它成为

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)

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

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)

...从来没有接触过JSON。并执行

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

loadResource :: ResourceRef -> IO Resource

这篇关于使用aeson为json中不可用的字段提供默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆