[英]How do I serialize an object with TimeSpan and Generic Lists to XML in C#?
我尝试使用XmlSerializer,但XmlSerializer不会序列化TimeSpan值; 它只是为timepans生成一个空标签(否则本来就是完美的)。
所以我尝试使用SoapFormatter,但SoapFormatter不会序列化通用列表; 这只会导致例外。
我还有其他选择吗? 我不能对我正在序列化的对象的类进行任何更改,因为它是从服务引用生成的。 因此,涉及更改课程的任何变通方法都已淘汰。
除了实现自定义序列化器,我别无选择吗? 我可以使用任何外部工具吗?
[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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.