.NET Core:从 API JSON 响应中删除空字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44595027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET Core: Remove null fields from API JSON response
提问by dotNetkow
On a global level in .NET Core 1.0 (all API responses), how can I configure Startup.cs so that null fields are removed/ignored in JSON responses?
在 .NET Core 1.0(所有 API 响应)的全局级别上,如何配置 Startup.cs 以便在 JSON 响应中删除/忽略空字段?
Using Newtonsoft.Json, you can apply the following attribute to a property, but I'd like to avoid having to add it to every single one:
使用 Newtonsoft.Json,您可以将以下属性应用于属性,但我想避免将其添加到每个属性中:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FieldName { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string OtherName { get; set; }
回答by dotNetkow
[.NET Core 1.0]
[.NET 核心 1.0]
In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:
在 Startup.cs 中,您可以将 JsonOptions 附加到服务集合并设置各种配置,包括删除空值,其中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
}
[.NET Core 3.1]
[.NET 核心 3.1]
Instead of:
代替:
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
Use:
用:
options.JsonSerializerOptions.IgnoreNullValues = true;
回答by TommyN
This can also be done per controller in case you don't want to modify the global behavior:
如果您不想修改全局行为,也可以按控制器执行此操作:
public IActionResult GetSomething()
{
var myObject = GetMyObject();
return new JsonResult(myObject, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
};
回答by charl botha
I found that for dotnet core 3 this solves it -
我发现对于 dotnet core 3 这解决了它 -
services.AddControllers().AddJsonOptions(options => {
options.JsonSerializerOptions.IgnoreNullValues = true;
});
回答by Glenox Andal
The code below work for me in .Net core 2.2
下面的代码在 .Net core 2.2 中对我有用
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
回答by Edgar Salazar
The following works for .NET Core 3.0, in Startup.cs > ConfigureServices():
以下适用于 .NET Core 3.0,在 Startup.cs > ConfigureServices() 中:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});

