JSON序列化 - 删除空键

Dal*_*ale 8 .net serialization json asp.net-web-api

我正在使用.Net Web API技术创建HTTP服务,我创建了一些DTO类,当只需要某个数据子集时,我打算只用这些数据填充DTO以最小化数据量转移.

有没有办法让JSON序列化程序忽略那些空的数据成员?我意识到[JsonIgnore]和[ScriptIgnore]属性将忽略特定成员,但我只想忽略它们,如果它们为null或为空.

[编辑]

感谢下面的LB.

我在WebApiConfig.cs中添加了以下内容以在Web API中启用它:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 14

Json.Net有一个这样的设置

var str = JsonConvert.SerializeObject(obj, 
    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
Run Code Online (Sandbox Code Playgroud)