【问题标题】:How to serialize only not null properties in derived class in Json.Net如何在 Json.Net 的派生类中仅序列化非空属性
【发布时间】:2017-02-16 13:09:23
【问题描述】:

实体对象需要转换为字符串以将它们存储在日志文件中以供人类阅读。 属性可以在运行时添加到派生实体。序列化在实体基类中定义。 我在下面尝试了代码,但它也返回具有空值的属性。 由于许多属性都有空值,这使得日志难以阅读。

Hoq 只序列化非空属性? 我也试过了

        var jsonSettings = new JsonSerializerSettings()
        {
            DefaultValueHandling = DefaultValueHandling.Ignore,
            Formatting = Formatting.Indented,
            TypeNameHandling= TypeNameHandling.All
        };
        return JsonConvert.SerializeObject(this, GetType(), jsonSettings);

这仅序列化了 newtonsoft json does not serialize derived class properties 中确认的 EntityBase 类属性

public class EntityBase {

        public string Serialize()
        {
            var s = new System.Web.Script.Serialization.JavaScriptSerializer();
            s.Serialize(this);

        }
     }

public class Customer: EntityBase {
  public string Name, Address;
  }

测试用例:

  var cust= new Customer() { Name="Test"};
  Debug.Writeline( cust.Serialize());

观察到:结果包含“地址”:null

预期:结果不应包含 Address 属性。

使用 ASP.NET/Mono MVC4、.NET 4.6

【问题讨论】:

  • 我根据这个尝试了TypeNameHandling= TypeNameHandling.All。还尝试使用JsonConvert.SerializeObject(this, GetType(), jsonSettings) 传递类型,但子类属性仍未序列化。
  • 属性可能在运行时添加到派生实体是什么意思。?你真的是指 runtime 吗?如果是这样,您的基类是否继承自 ExpandoObject 或类似的东西?
  • Json.NET 似乎工作正常。 Name 是序列化的,而 Address 不是。见dotnetfiddle.net/Xljh8U
  • 您的小提琴工作正常,但在 MVC 控制器中类似的代码不返回任何属性。不知道为什么

标签: c# json asp.net-mvc serialization json.net


【解决方案1】:

您可以创建自己的序列化程序来忽略空属性。

            JsonConvert.SerializeObject(
                object, 
                Newtonsoft.Json.Formatting.None, 
                new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多