【发布时间】:2013-01-07 08:13:30
【问题描述】:
我创建了一个将由移动应用程序使用的 ASP.Net WEB API 项目。我需要响应 json 来省略 null 属性,而不是将它们返回为 property: null。
我该怎么做?
【问题讨论】:
标签: c# asp.net-web-api
我创建了一个将由移动应用程序使用的 ASP.Net WEB API 项目。我需要响应 json 来省略 null 属性,而不是将它们返回为 property: null。
我该怎么做?
【问题讨论】:
标签: c# asp.net-web-api
在WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
或者,如果你想要更多的控制,你可以替换整个格式化程序:
var jsonformatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
};
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
【讨论】:
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore - 这将更新空值处理而不重置任何其他 json 序列化设置(例如使用小写在属性的第一个字母上)
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]。
我最终使用 ASP.NET5 1.0.0-beta7 在 startup.cs 文件中得到了这段代码
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
【讨论】:
对于 ASP.NET Core 3.0,Startup.cs 代码中的 ConfigureServices() 方法应包含:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
【讨论】:
您还可以使用[DataContract] 和[DataMember(EmitDefaultValue=false)] 属性
【讨论】:
如果您使用 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);
});
}
【讨论】: