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?
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.
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.
DataContractSerializer as the Default By default WCF uses the DataContractSerializer class to serialize data types.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With