目前部分,我想从我的api响应中排除空值,所以在我的startup.cs文件中,我有这个。
services.AddMvc()
.AddJsonOptions(options =>
{
// Setup json serializer
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
但是有可能说明在一个或多个控制器上,我实际上想要包含NULL值吗?
答案 0 :(得分:4)
一个选项是创建自定义Json结果类型,如此问题中所述:Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?。然后你可以在基本控制器上使用bool var并使用它在使用自定义Json
结果或甚至直接传递选项时禁用空值:
return Json(data, ignoreNulls: true);
答案 1 :(得分:0)
您可以从控制器代码中的JsonOutputFormatter
获取BindingContext.OutputFormatters
。它允许您动态更改SerializerSettings
。
尝试在控制器代码中包含using Newtonsoft.Json;
,并在控制器操作中执行以下操作:
var f = BindingContext.OutputFormatters.FirstOrDefault(
formatter => formatter.GetType() ==
typeof (Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter))
as Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter;
if (f != null) {
//f.SerializerSettings.Formatting = Formatting.Indented;
f.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}
我仅为我的测试添加Formatting = Formatting.Indented
,因为我们会立即看到结果。你不需要它。
更新:我使用没有身份验证的MVC Web应用程序创建了演示项目。然后我在HomeController
中添加了以下metod
public object TestMethod()
{
var testResult = new {
name = "Test",
value = 123,
nullableProperty = (string) null
};
return testResult;
}
并将项目的启动URL更改为Home/TestMethod
并启动演示。我能看到
{"name":"Test","value":123,"nullableProperty":null}
您不需要添加任何其他using语句来使用我最初发布的代码(只需要标准using Microsoft.AspNet.Mvc;
和using System.Linq;
),但如果代码可能更具可读性,你会using Microsoft.AspNet.Mvc.Formatters;
和using Newtonsoft.Json;
。我添加了Microsoft.AspNet.Mvc.Formatters
和Newtonsoft.Json
的using语句,并将代码修改为以下
public object TestMethod()
{
var testResult = new {
name = "Test",
value = 123,
nullableProperty = (string) null
};
var f = BindingContext.OutputFormatters.FirstOrDefault(
formatter => formatter.GetType() == typeof (JsonOutputFormatter)) as JsonOutputFormatter;
if (f != null) {
f.SerializerSettings.Formatting = Formatting.Indented;
f.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
}
return testResult;
}
输出结果现在看起来如下
{
"name": "Test",
"value": 123
}
标准代码在版本6.0.6中使用"Newtonsoft.Json"
。我们可以在依赖项中添加"Newtonsoft.Json": "8.0.2"
以使用最新版本的Newtonsoft.Json
。查看我在the issue中报告并且仍然打开的间接依赖关系的解决问题。
您可以从here下载测试项目。