如何设置 System.Runtime.Serialization
序列化程序忽略空值?
或者我必须使用 XmlSerializer
为了那个原因?如果是,怎么办?
(我不想写这样的<ecommerceflags i:nil="true"/>
标签,如果是null就跳过)
最佳答案
对于 System.Runtime.Serialization.DataContractSerializer
,您需要使用 [DataMember(EmitDefaultValue = false)]
标记该属性。
例如,下面的代码:
class Program
{
static void Main()
{
Console.WriteLine(SerializeToString(new Person { Name = "Alex", Age = 42, NullableId = null }));
}
public static string SerializeToString<T>(T instance)
{
using (var ms = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(ms, instance);
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember(EmitDefaultValue = false)]
public int? NullableId { get; set; }
}
打印以下内容:
<Person xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication4" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Age>42</Age>
<Name>Alex</Name>
</Person>
关于c# - 忽略空值 - 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142901/