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

.NET MVC Web API修改JSON响应:嵌套对象空值处理方案

解决Product无数据时返回null而非默认值对象的问题

我来帮你搞定这个问题!你现在的问题根源是不管有没有Product数据,都提前创建了一个Product实例,所以即使没有数据,这个对象也会带着int默认值0、string默认值空字符串被序列化,最终输出带默认值的对象。我们只需要调整初始化逻辑,让product在无数据时保持为null即可。

步骤1:修改Product的初始化逻辑

把原来无条件创建Product实例的代码,改成只有当数据表中有数据时才创建实例,否则设为null:

Profile_BO profile_BO = new Profile_BO();
foreach (DataRow dr in result.Tables[0].Rows) 
{ 
    profile_BO.Id = Convert.ToInt32(dr[0]); 
    profile_BO.Username = Convert.ToString(dr[1]); 
}

// 初始化product为null,只有当Tables[1]有数据时才赋值
Product product = null;
if (result.Tables[1].Rows.Count > 0)
{
    product = new Product();
    foreach (DataRow dr1 in result.Tables[1].Rows) 
    { 
        product.Id = Convert.ToInt32(dr1[0]); 
        product.Type = Convert.ToString(dr1[1]); 
    }
}
profile_BO.product = product;

步骤2:确保JSON序列化配置正确

默认情况下,.NET的JSON序列化器(不管是System.Text.Json还是Newtonsoft.Json)都会把null值的属性序列化为"product": null,但如果你的项目有自定义序列化配置,需要检查以下几点:

如果使用System.Text.Json(ASP.NET Core默认)

确保没有设置忽略null值的配置,或者明确设置保留null值:

// 在Program.cs或者Startup.cs的服务配置中
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 确保当属性为null时依然输出该属性(默认就是这个行为,可省略)
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;
    });

如果使用Newtonsoft.Json(Json.NET)

确保配置了包含null值:

builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    });

验证结果

修改后,当没有Product数据时,返回的JSON就会变成你期望的格式:

{ "Id": 1, "Username": "abc", "product": null }

内容的提问来源于stack exchange,提问作者Niteesh Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:46:31