如何设置System.Runtime.Serialization
序列化程序忽略空值?我需要使用XmlSerializer
吗?如果是这样,怎么样?忽略空值 - 序列化
(我不想<ecommerceflags i:nil="true"/>
标签像这样写,如果是null,则只是跳过)
如何设置System.Runtime.Serialization
序列化程序忽略空值?我需要使用XmlSerializer
吗?如果是这样,怎么样?忽略空值 - 序列化
(我不想<ecommerceflags i:nil="true"/>
标签像这样写,如果是null,则只是跳过)
你需要的财产与[DataMember(EmitDefaultValue = false)]
标记System.Runtime.Serialization.DataContractSerializer
。
例如,下面的代码:
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>
谢谢。这是我正在寻找的。最干净和最简单的解决方案。 – matteeyah
虽然它有少值(但是它可以在序列化流短),您可以自定义序列化来实现这一点。
使用System.Runtime.Serialization
,您可以实现ISerializable
接口:
[Serializable]
public class MyClass: ISerializable
{
private string stringField;
private object objectField;
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (stringField != null)
info.AddValue("str", stringField);
if (objectField != null)
info.AddValue("obj", objectField);
}
// the special constructor for deserializing
private MyClass(SerializationInfo info, StreamingContext context)
{
foreach (SerializationEntry entry in info)
{
switch (entry.Name)
{
case "str":
stringField = (string)entry.Value;
break;
case "obj":
objectField = entry.Value;
break;
}
}
}
}
当使用XML序列化,可以实现IXmlSerializable
界面自定义输出以类似的方式。
至于我读,你可以使用指定的特征
public int? Value { get; set; }
[System.Xml.Serialization.XmlIgnore]
public bool ValueSpecified { get { return this.Value != null; } }
要仅在网络中指定它写。
另一种方式是
[System.Xml.Serialization.XmlIgnore]
private int? value;
public int Value { get { value.GetValueOrDefault(); } }
你序列化是什么类型,它是空? Nullables?字符串? – SlapY
Nullables。可为空的整数,双精度,小数,... – matteeyah