您的位置:首页 > Web前端 > JavaScript

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

2017-06-15 16:02 609 查看
从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也同样有作用,一次代码,两处生效,很方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐