JSON Date Serialization C# Snippet

JSON Date Serialization C# Snippet

When exposing .Net DateTime members to service consumers the .Net format is not always appropriate because the consumer may not be on the .Net platform. Therefore it’s best to use the ISO 8601 standard.

Serialization is performed in .Net by using the OnSerializing attribute, and deserialization by using the OnDeserialized attribute.

I created a Visual Studio snippet that writes the code that enables you to serialize/deserialize your DateTime member. Once added to your Snippets library utilize it by typing “jsd” in a C# code file and press Tab, then change the highlighted “VariableName” to the name that you want to use for the DataMember and press Enter. Every occurrence of “VariableName” will be changed to what you typed.

This is the code that gets generated to serialize/deserialize member “MyJsonDate”:

#region "MyJsonDate"
 public DateTime MyJsonDate { get; set; }

 [DataMember(Name = "MyJsonDate")]
 private string MyJsonDateIso { get; set; }

 private void OnSerializingMyJsonDate(StreamingContext ctx)
     MyJsonDateIso = MyJsonDate.ToString("O");

 private void OnDeserializedMyJsonDate(StreamingContext ctx)
     if (string.IsNullOrEmpty(MyJsonDateIso))
         MyJsonDate = default(DateTime);
         DateTime dateValue;
     	 MyJsonDate = DateTime.TryParse(MyJsonDateIso, out dateValue) ? 
                 dateValue : default(DateTime);

Here’s the snippet that produces the above code:

<?xml version="1.0" encoding="utf-8"?>
  <CodeSnippet Format="1.0.0">
      <Title>Json Date Serialization Code Generator</Title>
      <Description>Template for constructing the serializing code for DateTime types.
          <ToolTip>Replace with the name of the DateTime variable.</ToolTip>
          <ToolTip>Replace with a DateTime variable in your application.</ToolTip>
      <Code Language="CSharp">
        #region "$VariableName$"
	public DateTime $VariableName$ { get; set; }
	[DataMember(Name = "$VariableName$")]
        private string $VariableName$Iso { get; set; }
	[OnSerializing] private void OnSerializing$VariableName$(StreamingContext ctx)
            $VariableName$Iso = $VariableName$.ToString("O");
	[OnDeserialized] private void OnDeserialized$VariableName$(StreamingContext ctx)
            if (string.IsNullOrEmpty($VariableName$Iso))
                $VariableName$ = default(DateTime);
                DateTime dateValue;
                $VariableName$ = DateTime.TryParse($VariableName$Iso, out dateValue) ? dateValue : default (DateTime);


Leave a Reply

Your email address will not be published. Required fields are marked *