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

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

问题描述

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

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?

使用Newtonsoft.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:

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

推荐答案

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

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:从API JSON响应中删除空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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