Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize an object with TimeSpan and Generic Lists to XML in C#?

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?

like image 662
ATDeveloper Avatar asked Nov 16 '10 15:11

ATDeveloper


1 Answers

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>
like image 91
Nick Martyshchenko Avatar answered Oct 05 '22 16:10

Nick Martyshchenko