1

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.

blackwolf123333
  • 313
  • 4
  • 13
  • Where _is_ that information supposed to come from, if not from the JSON input? – leftaroundabout Oct 18 '17 at 13:18
  • The picture is loaded later, after reading the json, and at that time the loaded field will be set as well. I guess a loaded could be false by default, but the question remains how to do that. – blackwolf123333 Oct 18 '17 at 13:19
  • 1
    But then what should the value of `res` be, when the picture is not loaded? Since this isn't java it can't be `null`, it has to be a picture. If want it to be able to be `null` you have to change the type to `Maybe Picture`. – Julia Path Oct 18 '17 at 13:22
  • I guess I could try that, same for loaded. Make them both Maybe – blackwolf123333 Oct 18 '17 at 13:25
  • Defining res as Maybe Picture still gives an error: No instance for (FromJSON Picture) – blackwolf123333 Oct 18 '17 at 13:27

1 Answers1

4

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
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319