C#里XML(JSON)序列化时,自动隐藏值为Null的成员的输出

从StackOverflow里找到的答案。发现对最新的Newtownsoft的JSON序列化也同样适用。

https://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

举例子:

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

用以下代码序列化:

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

得到序列化结果,没有AGE

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

意外的收货,对Newtonsoft也同样有作用,一次代码,两处生效,很方便。

原文地址:https://www.cnblogs.com/easyc/p/XML_Json_Serialization_Automatic_Hide_Field_When_Its_Value_is_Null.html