在 ASP.NET Web API 上取消具有空值的属性

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

我怎么能这么做?

49337 次浏览

In the WebApiConfig:

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

Or, if you want more control, you can replace entire formatter:

var jsonformatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
};


config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);

If you are using vnext, in vnext web api projects, add this code to startup.cs file.

    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);
});


}

I ended up with this piece of code in the startup.cs file using ASP.NET5 1.0.0-beta7

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

You can also use [DataContract] and [DataMember(EmitDefaultValue=false)] attributes

For ASP.NET Core 3.0, the ConfigureServices() method in Startup.cs code should contain:

services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});

Since I cannot comment due to my low reputation. Adding to Dave Wegner's answer since it is obsolete the current solution is:

services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
);