Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize old data for a type that has changed?

I have data that has been stored using binary serialization for the following class:

[Serializable]
public abstract class BaseBusinessObject
{
    private NameValueCollection _fieldErrors = new NameValueCollection();

    protected virtual NameValueCollection FieldErrors
    {
        get { return _fieldErrors; }
        set { _fieldErrors = value; }
    }

    ...
}

At some point, the class was changed to this:

[Serializable]
public abstract class BaseBusinessObject
{
    private Dictionary<string, string> _fieldErrors = new Dictionary<string, string>();

    protected virtual Dictionary<string, string> FieldErrors
    {
        get { return _fieldErrors; }
        set { _fieldErrors = value; }
    }

    ...
}

This is causing issues deserializing old data.

My first thought was to implement ISerializable, but this class has numerous properties as well as hundreds of inheriting classes that I would have to implement this for as well.

I would like to either change the old data to match the current structure during deserialization or have a clean way of upgrading the old data.

like image 572
ramnik Avatar asked Aug 11 '09 14:08

ramnik


2 Answers

Add the new _fieldErrors under a different name, say _fieldErrors2, and make it [Optional]. Then implement an [OnDeserialized] Method that copies the data from _fieldErrors to _fieldErrors2 (if present), and clears _fieldErrors.

like image 198
Martin v. Löwis Avatar answered Sep 25 '22 05:09

Martin v. Löwis


If the data is only used internally, my first thought would be to write some simple throw-away code to de-serialize your binary data using the old "NameValueCollection", map it to a Dictionnary and re-serialize it. Even if it'll take a few days to process all the data, it doesn't seem worth it to implement a patch on your new code to support the old data.

Even if it's not only used internally, an importer seems like the simplest way to go.

like image 25
OlivierD Avatar answered Sep 25 '22 05:09

OlivierD