.NET 5全局配置Newtonsoft.Json序列化与反序列化不同空值处理
解决方案:全局配置Newtonsoft.Json实现反序列化忽略null、序列化保留null
你的核心需求是反序列化请求体时忽略JSON中的null属性,序列化响应时保留模型的null属性,在.NET 5中可以通过分别配置Newtonsoft.Json的输入、输出格式化器来实现,修改你的ConfigureServices代码如下:
using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { // 响应序列化:保留null值,输出到JSON中 options.SerializerSettings.NullValueHandling = NullValueHandling.Include; // 保持属性为PascalCase,不自动转camelCase if (options.SerializerSettings.ContractResolver is DefaultContractResolver resolver) { resolver.NamingStrategy = null; } // 请求反序列化:忽略JSON中的null属性,不覆盖模型默认值 var inputFormatter = options.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().FirstOrDefault(); if (inputFormatter != null) { inputFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; } // 兼容原配置:允许从字符串读取数字(对应原System.Text.Json的NumberHandling设置) options.SerializerSettings.FloatParseHandling = FloatParseHandling.Decimal; }); }
关键说明:
- 拆分序列化/反序列化配置:全局
SerializerSettings设置Include保证响应输出保留null,单独修改输入格式化器的SerializerSettings为Ignore,让请求反序列化时忽略null值,实现两种场景的不同行为。 - 移除无用的AddJsonOptions:添加
AddNewtonsoftJson后,ASP.NET Core会替换默认的System.Text.Json格式化器,原AddJsonOptions的配置不会生效,所以把相关设置迁移到Newtonsoft的配置中。 - .NET 5问题原因:.NET 5默认用System.Text.Json,和你原来.NET Framework依赖的Newtonsoft.Json默认行为、配置逻辑差异很大,即使你加了AddNewtonsoftJson,全局统一的NullValueHandling会同时影响序列化和反序列化,导致不符合预期的结果。
内容的提问来源于stack exchange,提问作者ilker
相关产品推荐
相关产品推荐

