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

时间:2023-03-09 16:44:35
C#里XML(JSON)序列化时,自动隐藏值为Null的成员的输出

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

https://*.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也同样有作用,一次代码,两处生效,很方便。