.NET 8中JSON值无法转换为System.Int32问题的解决方法
.NET 8中解决JSON非可空字段绑定null报错的方案
问题根源
.NET 4.7.2默认采用Newtonsoft.Json处理JSON,它会自动将null转换为非可空值类型的默认值(如int对应0);而.NET 8默认使用System.Text.Json,其类型校验逻辑更严格,当JSON中的null绑定到非可空值类型时,会直接抛出「The JSON value could not be converted to System.Int32」错误。
可行解决方案
1. 修改DTO为可空值类型(推荐)
将DTO中的非可空值类型字段改为可空值类型,既让代码语义与业务逻辑匹配,又能直接兼容JSON中的null值:
public class Party { public int? Id { get; set; } } public class OrganizationParty { public int? Id { get; set; } }
2. 配置System.Text.Json宽松处理null值
若无需修改DTO结构,可通过配置让System.Text.Json允许将null转换为非可空值类型的默认值:
builder.Services.AddControllers(configure => { configure.Filters.Add<ExceptionFilterAttribute>(); configure.AllowEmptyInputInBodyModelBinding = true; }).AddJsonOptions(opt => { opt.JsonSerializerOptions.PropertyNamingPolicy = null; // 允许null绑定到非可空值类型,自动使用类型默认值 opt.JsonSerializerOptions.AllowNullOnNonNullableTypes = true; });
3. 切换回Newtonsoft.Json(完全兼容旧行为)
如果需要1:1复刻.NET 4.7.2的JSON处理逻辑,可切换回Newtonsoft.Json:
- 首先安装NuGet包:
Microsoft.AspNetCore.Mvc.NewtonsoftJson - 然后修改Program.cs的配置:
builder.Services.AddControllers(configure => { configure.Filters.Add<ExceptionFilterAttribute>(); configure.AllowEmptyInputInBodyModelBinding = true; }).AddNewtonsoftJson(opt => { // 保持属性命名与原代码一致 opt.SerializerSettings.ContractResolver = new DefaultContractResolver(); });
内容的提问来源于stack exchange,提问作者Venkat Singri
相关产品推荐
相关产品推荐

