Friday, February 3, 2012

How to Serialize and Deserialize a class containing DateTimeOffset members in C#

The proper way to serialize and deserialize DateTimeOffset in XML is to use the DataContractSerializer instead of the standard XmlSerializer.  The reason is that the XMLSerializer does not support certain aspects of the DateTimeOffset structure (don't ask me what they are, but that's what Microsoft states is their reasoning for not supporting it).  I tend to try and code using generics whenever possible, especially when it's stuff like this.

Thus, here's an example of how to serialize any class using it (I'm using UTF8 encoding here, but you can use whatever you like):
     public static string SerializeObject<T>(T instance) where T : class  
     {  
       try  
       {  
         MemoryStream stream = new MemoryStream();  
         DataContractSerializer serializer = new DataContractSerializer(typeof(T));  
         serializer.WriteObject(stream, instance);  
         return new UTF8Encoding().GetString(stream.ToArray());  
       }  
       catch(Exception ex)  
       {  
         ...  
       }  
     }  
And here's how to deserialize it again:
     public static T DeserializeObject<T>(string data) where T : class  
     {  
       try  
       {  
         MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(data));  
         DataContractSerializer serializer = new DataContractSerializer(typeof(T));  
         return (T)serializer.ReadObject(memoryStream);  
       }  
       catch  
       {  
         ...  
       }  
     }  

No comments: