【问题标题】:How do I serialize an object with TimeSpan and Generic Lists to XML in C#?如何在 C# 中将具有 TimeSpan 和通用列表的对象序列化为 XML?
【发布时间】:2016-06-20 02:56:57
【问题描述】:

我尝试使用 XmlSerializer,但 XmlSerializer 不会序列化 TimeSpan 值;它只是为时间跨度生成一个空标签(否则会很完美)。

然后我尝试使用 SoapFormatter,但 SoapFormatter 不会序列化通用列表;这只会导致异常。

我还有什么其他选择?我无法对我正在序列化的对象的类进行任何更改,因为它是从服务引用生成的。因此,任何涉及更改类的解决方法都已失效。

我是否别无选择,只能实现自定义序列化程序?有没有我可以使用的外部工具?

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    您可以使用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);
    

    结果:

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

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2017-12-15
        • 2010-10-12
        • 2018-10-11
        • 1970-01-01
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 2014-11-27
        • 1970-01-01
        相关资源
        最近更新 更多