You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让返回Dynamic类型的Post API保留null值属性?

解决方案

1. 修正类属性的类型

首先你的代码存在编译错误:int是值类型,无法赋值为null。要实现赋值null的需求,必须将属性改为可空值类型(int?):

public class ModDetailResponse
{
    public int element1 { get; set; }
    public int? element2 { get; set; } // 修改为可空int类型
}

2. 配置JSON序列化保留null属性

默认情况下,.NET的JSON序列化器会自动忽略值为null的属性,需修改序列化配置强制输出这类属性,分两种常见序列化工具说明:

情况一:使用System.Text.Json(ASP.NET Core 3.0+默认)

在.NET 6+的Program.cs或.NET 5及更早的Startup.cs中全局配置:

// .NET 6+ Program.cs
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 强制保留所有属性,包括null值的属性
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;
        // 也可单独针对null配置:options.JsonSerializerOptions.IgnoreNullValues = false;
    });

情况二:使用Newtonsoft.Json(Json.NET)

若项目依赖Newtonsoft.Json,全局配置如下:

// .NET 6+ Program.cs
builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    });

3. 局部配置(仅针对单个类/属性)

如果不想全局修改序列化规则,可通过特性单独配置目标属性或类:

System.Text.Json 局部配置

public class ModDetailResponse
{
    public int element1 { get; set; }
    [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
    public int? element2 { get; set; }
}

Newtonsoft.Json 局部配置

public class ModDetailResponse
{
    public int element1 { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Include)]
    public int? element2 { get; set; }
}

完成上述配置后,当element2赋值为null时,API响应会返回:

{"element1":123,"element2":null}

内容的提问来源于stack exchange,提问作者Alisha Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:05:19