Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override deserialization in C#

I've got a class that will undergo certain version changes over the course of time. The data from inside this class is serialized and deserialized as part of the startup of my application. The problem I have is if I update the class by adding more properties, and then start the application, the old data does not get loaded properly.
What I'm looking to do is override the deserialization step, I don't mind manually reconstructing the object from xml, as I have a version number stored and can use it to recursively update versions of the object.

Is there an interface I can implement, or an attribute I can set somewhere, to be able to do this?

If you can't think of a way to do what I want, are there alternatives? such as defaulting values for properties that may not exist in the version of the xml I am loading.

like image 419
Jean-Bernard Pellerin Avatar asked Aug 13 '10 21:08

Jean-Bernard Pellerin


People also ask

What is deserialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What is the difference between serialize and deserialize?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.

What is the deserialization process?

Deserialization is the process of reconstructing a data structure or object from a series of bytes or a string in order to instantiate the object for consumption. This is the reverse process of serialization, i.e., converting a data structure or object into a series of bytes for storage or transmission across devices.

What is deserialization XML?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


2 Answers

Implement the IXmlSerializable interface.

like image 145
SLaks Avatar answered Oct 24 '22 09:10

SLaks


Typically for versioning, you can use the OptionalField attribute to newly added members that might cause compatibility problems. During serialization, if member was not serialized, this leaves members value as null rather than throwing the exception.

Also, take a look at IDeserializationCallback.OnDeserialization interface which allows you to customize your deserialization.

like image 32
Punit Vora Avatar answered Oct 24 '22 10:10

Punit Vora