Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional properties when deserializing a DataContract/Serializable mish-mash

I have an existing codebase that persists a couple of simple classes to disk via NetDataContractSerializer, but the classes are unfortunately not adorned with [DataContract], but rather with [Serializable]. This works fine, but now I want to add a few new properties to the persisted classes, while still be able to read the files generated by the old version.

Let's say this is the class:

[Serializable]
public class Persisted
{
    public int OldProperty {get;set;}
    public int NewProperty {get;set;}
}

Now, when I deserialize the old files, I get an exception because they don't contain NewProperty. This makes sense. So I wanted to have NewProperty ignored, but while there's a [OptionalField] attribute to have the serializer ignore the missing field, it can't be applied to properties - only fields.

So I figured I'll use [DataContract] and [DataMember], which also has an IsRequired property, but this changes the layout of the serialized file, and it can't read the old data files. Moreover, you can't mix [Serializable] and [DataMember] - if the serializer sees the [Serializable] attribute, it ignores the [DataMember] directives.

So, barring the option to do a one-time conversion of the old files (possible, but not my first choice), is there a way to get the NetDataContractSerializer to ignore a field in an existing XML serialized object?

like image 378
Avner Shahar-Kashtan Avatar asked Mar 26 '12 10:03

Avner Shahar-Kashtan


People also ask

What does serializing and Deserializing mean?

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.

Does deserialization call constructor c#?

Constructors are not called when objects are deserialized. Therefore, any logic that executes during normal construction needs to be implemented as one of the serialization callbacks.

Which namespace is used for serialization in WCF?

DataContractSerializer as the Default By default WCF uses the DataContractSerializer class to serialize data types.


1 Answers

The problem is that when using the Serializable attribute, what gets serialized are fields, not properties. Since you're using auto-properties, the fields are hidden and you can't add attributes to them.

The solution is simple - don't use auto-properties.

like image 51
Eli Arbel Avatar answered Nov 03 '22 21:11

Eli Arbel