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; }

 [OnSerializing]
 private void OnSerializingMyJsonDate(StreamingContext ctx)
 {
     MyJsonDateIso = MyJsonDate.ToString("O");
 }

 [OnDeserialized]
 private void OnDeserializedMyJsonDate(StreamingContext ctx)
 {
     if (string.IsNullOrEmpty(MyJsonDateIso))
         MyJsonDate = default(DateTime);
     else
     {
         DateTime dateValue;
     	 MyJsonDate = DateTime.TryParse(MyJsonDateIso, out dateValue) ? 
                 dateValue : default(DateTime);
     }
 }
 #endregion

Here’s the snippet that produces the above code:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Json Date Serialization Code Generator</Title>
      <Description>Template for constructing the serializing code for DateTime types.
      </Description>
      <Shortcut>jsd</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>VariableName</ID>
          <ToolTip>Replace with the name of the DateTime variable.</ToolTip>
          <Default>Variable_Name</Default>
        </Literal>
        <Object>
          <ID>VariableName</ID>
          <Type>System.DateTime</Type>
          <ToolTip>Replace with a DateTime variable in your application.</ToolTip>
          <Default>DateTimeVariable</Default>
        </Object>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[
        #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);
            else
            {
                DateTime dateValue;
                $VariableName$ = DateTime.TryParse($VariableName$Iso, out dateValue) ? dateValue : default (DateTime);
            }
        }
        #endregion]]>
      </Code>

    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Leave a Reply

Your email address will not be published.