Is it possible to programmatically set that you want to exclude a property from serialization?
Example:
In XML Serializing, you can use the [XmlIgnore] attribute (System. Xml. Serialization. XmlIgnoreAttribute) to ignore a property when serializing a class.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.
I believe there are three options here:
Use XmlIgnore attribute. The downside is that you need to know in advance which properties you want the xmlserializer to ignore.
Implement the IXmlSerializable interface. This gives you complete control on the output of XML, but you need to implement the read/write methods yourself.
Implement the ICustomTypeDescriptor interface. I believe this will make your solution to work no matter what type of serialization you choose, but it is probably the lengthiest solution of all.
It depends on serialization type. Here full example for doing this with BinaryFormatter:
You may use OnDeserializedAttribute:
[Serializable]
class SerializableEntity
{
[OnDeserialized]
private void OnDeserialized()
{
id = RetrieveId();
}
private int RetrievId() {}
[NonSerialized]
private int id;
}
And there is another way to do this using IDeserializationCallback:
[Serializable]
class SerializableEntity: IDeserializationCallback
{
void IDeserializationCallback.OnDeserialization(Object sender)
{
id = RetrieveId();
}
private int RetrievId() {}
[NonSerialized]
private int id;
}
Also you may read great Jeffrey Richter's article about serialization: part 1 and part 2.
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