在ASP.NET Web API上抑制具有空值的属性

我已经创build了一个将被移动应用程序使用的ASP.Net WEB API项目。 我需要响应json来省略null属性,而不是将它们返回为property: null

我怎样才能做到这一点?

WebApiConfig

 config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; 

或者,如果你想要更多的控制,你可以replace整个格式化程序:

  var jsonformatter = new JsonMediaTypeFormatter { SerializerSettings = { NullValueHandling = NullValueHandling.Ignore } }; config.Formatters.RemoveAt(0); config.Formatters.Insert(0, jsonformatter); 

我结束了使用ASP.NET5 1.0.0-beta7的startup.cs文件中的这段代码

 services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); 

如果您正在使用vnext,请在vnext web api项目中将此代码添加到startup.cs文件。

  public void ConfigureServices(IServiceCollection services) { services.AddMvc().Configure<MvcOptions>(options => { int position = options.OutputFormatters.FindIndex(f => f.Instance is JsonOutputFormatter); var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; var formatter = new JsonOutputFormatter(); formatter.SerializerSettings = settings; options.OutputFormatters.Insert(position, formatter); }); } 

我知道这个线程已经有好几年了,但是如果你回到JSON.NET文档,它已经详细地讨论了如何处理减less不同情况下的序列化JSON大小的问题,比如忽略所有null,忽略所有默认值,忽略只有特定属性的空值或默认值等:

http://www.newtonsoft.com/json/help/html/reducingserializedjsonsize.htm