Conditional serialization using Csharp
Conditional serialization using Csharp
Sometimes you need to serialize attributes according to conditions and properties of your own class, you can do that use the ShouldSerialize method. This method is used by different serialization libraries, for example: System.Xml.Serialization, Newtonsoft.Json (a popular JSON framework for .NET).
The following syntax shows the declaration of ShouldSerialize method:
Example
The following example shows the implementation of ShouldSerialize method on the serialization of a JSON object.
Model class:
The method ShouldSerializeCreateDate is used to put a condition on the attribute serialization CreateDate: if the TelefilmName is equal to “Californication” then the CreateDate attribute won’t be serialized.