Search Unity

How to safely deserializing morphing file structures

Discussion in 'Scripting' started by malkere, Jul 26, 2017.

  1. malkere

    malkere

    Joined:
    Dec 6, 2013
    Posts:
    1,212
    I'm thinking this is impossible via the direct approach, but I'll ask.

    Say I have a serializable class Stringy with string A and string B that I've written off to the hard disk. In a later version string C gets added to the class Stringy. Now if I try to read the old files they will expect a string C in any Stringy instance and will throw errors.

    Is there any common or best practice way to deal with this?

    To expand, I wrap all my files in classes. PlayerDataHolder has playerLevel, playHealth, etc. I can just write it off to disk, pull it back off disk, and all the variables are there and good. If I want to add playerDexterity later on though all the old saved files won't load with the modern loader. Can I:
    1. Create a new class PlayerDataHolder2 with playerDexterity in it, and attempt to input the file as a PlayerDataHolder if it failed to load as a PlayerDataHolder2.
    2. Make a generic DataHolder empty class and make all of my saved files inherent of it, instead detecting the object type after I've read it off the disk.
    3. Some way to detect file type (not via extension/name) prior to deserialization?
    Number 2 sounds like cheating... I'm going to try that when I get home. Has anyone managed something like this before?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Have you investigated a text based solution, like JSON serialization? Unity has a built in JSONUtility class, and there are dozens of libraries on the internet as well.

    The general idea is you don't serialize the class by just dumping its binary to a file. Instead you serialize the field names and the associated data as text. Then on loading you can just load the fields that match the current class structure. You can drop fields that you have removed, and create default values for new fields.
     
  3. malkere

    malkere

    Joined:
    Dec 6, 2013
    Posts:
    1,212
    Gah! I spent hours last night coding and never made it to my new saveData challenges, lol... never enough time in the day.

    Thank you for the reply Kiwasi, that makes sense, sort of a automatic string break up process right? Just handled behind the scenes instead of converting everything manually. That still sounds less awesome, but I'll definitely run some tests to see whose fast and awesome.

    It's not a problem I expect to run into a ton, it's just something foreseeable I wasn't sure how to approach.
     
  4. malkere

    malkere

    Joined:
    Dec 6, 2013
    Posts:
    1,212
    I've also found that using a weak cast:

    Code (CSharp):
    1. AvatarData avatarData = fileData as AvatarData;
    will return the varible as null if it does not fit instead of throwing an error