zoukankan      html  css  js  c++  java
  • 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也同样有作用,一次代码,两处生效,很方便。

  • 相关阅读:
    灰度发布
    rabbitmq应用场景
    redis设置cpu核数与内存
    使用word2010发布博客到博客园
    讲师
    UML-6.3-用例-详述示例
    UML-6.2-用例-用例模型/用例/场景关系
    UML-6.1-用例-示例
    数据库增量同步开源软件
    UML-5-进化式需求
  • 原文地址:https://www.cnblogs.com/easyc/p/XML_Json_Serialization_Automatic_Hide_Field_When_Its_Value_is_Null.html
Copyright © 2011-2022 走看看