.NET Core:从 API JSON 响应中删除空字段 [英] .NET Core: Remove null fields from API JSON response

查看:34
本文介绍了.NET Core:从 API JSON 响应中删除空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .NET Core 1.0 的全局级别(所有 API 响应),我如何配置 Startup.cs 以便在 JSON 响应中删除/忽略空字段?

使用 Newtonsoft.Json,您可以将以下属性应用于属性,但我想避免将其添加到每个属性:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]公共字符串字段名称 { 获取;放;}[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]公共字符串其他名称 { 获取;放;}

解决方案

[.NET Core 1.0]

在 Startup.cs 中,您可以将 JsonOptions 附加到服务集合并设置各种配置,包括删除空值,其中:

public void ConfigureServices(IServiceCollection services){服务.AddMvc().AddJsonOptions(options => {options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;});}

[.NET Core 3.1]

代替这一行:

options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

使用:

options.JsonSerializerOptions.IgnoreNullValues = true;

[.NET 5.0]

代替上述两种变体,使用:

 options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

.NET Core 3.1 中的变体仍然有效,但它被标记为 NonBrowsable(因此您永远不会获得有关此参数的 IntelliSense 提示),因此它很可能会在某个时候过时.

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?

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:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FieldName { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string OtherName { get; set; }

解决方案

[.NET Core 1.0]

In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc()
             .AddJsonOptions(options => {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
     });
}

[.NET Core 3.1]

Instead of this line:

options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

Use:

options.JsonSerializerOptions.IgnoreNullValues = true;

[.NET 5.0]

Instead of both variants above, use:

 options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

The variant from .NET Core 3.1 still works, but it is marked as NonBrowsable (so you never get the IntelliSense hint about this parameter), so it is very likely that it is going to be obsoleted at some point.

这篇关于.NET Core:从 API JSON 响应中删除空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆