我已经创建了一个移动应用程序将使用的ASP.Net WEB API项目。我需要响应json省略null属性,而不是将它们作为property: null
返回。
我该怎么做呢?
发布于 2013-01-24 02:25:50
在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);
发布于 2015-10-16 17:44:23
最后,我使用ASP.NET5 1.0.0-beta7在startup.cs文件中编写了这段代码
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
发布于 2019-11-15 23:43:51
对于ASP.NET Core3.0,Startup.cs
代码中的ConfigureServices()
方法应该包含:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
https://stackoverflow.com/questions/14486667
复制相似问题