Last active
January 13, 2020 02:01
-
-
Save joe-oli/818b034fd58e89415d24778762caabca to your computer and use it in GitHub Desktop.
How to Serialize and Deserialize a class containing DateTimeOffset Property in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DateTimeOffset fails silently with XmlSerializer; instead use DataContractSerializer. | |
Apparently XMLSerializer does not support certain aspects of the DateTimeOffset structure.. WTF?! | |
Generic example below (uses 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) | |
{ | |
... | |
} | |
} | |
OR with no err handling, let the consumer handle error: | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
DataContractSerializer dcSerz = new DataContractSerializer(typeof(T)); | |
dcSerz.WriteObject(stream, instance); | |
string resultAsXml = new UTF8Encoding().GetString(stream.ToArray()); | |
return resultAsXml; | |
} | |
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 | |
{ | |
... | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment