在 ASP.NET Web API 上抑制具有空值的属性 [英] Suppress properties with null value on ASP.NET Web API
本文介绍了在 ASP.NET Web API 上抑制具有空值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个供移动应用程序使用的 ASP.Net WEB API 项目.我需要响应 json 来省略 null 属性,而不是将它们作为 property: null
返回.
I've created an ASP.Net WEB API Project that will be used by a mobile application. I need the response json to omit null properties instead of return them as property: null
.
我该怎么做?
推荐答案
在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);
这篇关于在 ASP.NET Web API 上抑制具有空值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文