I tried using XmlSerializer, but XmlSerializer will not serialize a TimeSpan value; it just generates an empty tag for timespans (otherwise would have been perfect).
So then I tried using SoapFormatter, but SoapFormatter will not serialize generic lists; that just results in an exception.
What other options do I have? I can't make any change to the class of the object I'm serializing because it's generated from a service reference. So any workarounds that involve changing the class are out.
Do I have no choice but to implement a custom serializer? Are there any external tools I could use?
You can use DataContractSerializer
[DataContract]
public class TestClass
{
// You can use List<T> or other generic collection
[DataMember]
public HashSet<int> h { get; set; }
[DataMember]
public TimeSpan t { get; set; }
public TestClass()
{
h = new HashSet<int>{1,2,3,4};
t = TimeSpan.FromDays(1);
}
}
var o = new TestClass();
ms = new MemoryStream();
var sr = new DataContractSerializer(typeof(TestClass));
sr.WriteObject(ms, o);
File.WriteAllBytes("test.xml", ms.ToArray());
ms = new MemoryStream(File.ReadAllBytes("test.xml"));
sr = new DataContractSerializer(typeof(TestClass));
var readObject = (TestClass)sr.ReadObject(ms);
Result:
<TestClass xmlns="http://schemas.datacontract.org/2004/07/Serialization" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><h xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><a:int>1</a:int><a:int>2</a:int><a:int>3</a:int><a:int>4</a:int></h><t>P1D</t></TestClass>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With