Not logged in - Login

Perform custom actions during JSON Serialization

The following illustrates how to perform custom serialization actions during serialization events on a JSON object.

[DataContract]
public class ApptInfo
{
   [DataMember]
   public int id { get; set; }

   public TimeSpan duration { get; set; }
   [DataMember(Name = "duration"]
   private string duration_serialized { get; set; }

   [OnSerializing] // this attribute specifies that this method should be called during the serialization of the object.
   void OnSerializing(StreamingContext context)
   {
      // do custom actions on serialization
      if (this.duration == null)
      {
         this.duration_serialized = null;
      }
      else
      {
         this.duration_serialized = string.Format(@"{0:hh\:mm\:ss}", this.duration);
      }
   }

   [OnDeserializing] // this attribute specifies that this method should be called during the Deserialization of the object.
   void OnDeserializing(StreamingContext context)
   {
      // do some custom actions on deserialization
      TimeSpan tsParse;
      if (string.IsNullOrWhiteSpace(this.duration_serialized))
      {
         this.duration = new TimeSpan();
      }
      else if (TimeSpan.TryParse(this.duration_serialized, out tsParse))
      {
         this.duration = tsParse;
      }
      else
      {
         this.duration = new TimeSpan();
      }
   }
}