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

.NET Framework 4.6.2 Controller无法读取Payload中的嵌套对象值

问题:.NET Framework 4.6.2中嵌套对象JSON反序列化失败,属性全为false

问题场景

项目基于.NET Framework 4.6.2,Controller接收包含嵌套对象的数组参数时,外层对象的属性(如Name)能正确读取,但嵌套的Pets对象所有属性均显示为默认值false,无法正确反序列化前端传入的JSON数据。

前端提交的JSON Payload示例:

const customerList = [
  {
    Name: 'John',
    Pets: {
      Cat: false,
      Dog: false,
      Bird: false,
      Mouse: true,
    },
  },
  {
    Name: 'Mary',
    Pets: {
      Cat: false,
      Dog: false,
      Bird: false,
      Mouse: true,
    },
  },
];

const data = { customerList };

await fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data),
});

后端模型代码:

public class Customer
{
    public string Name { get; set; }
    public Pets Pets { get; set; }
}

public class Pets
{
    public bool Cat;
    public bool Dog;
    public bool Bird;
    public bool Mouse;
}

问题原因

ASP.NET MVC在.NET Framework 4.6.2中默认使用Newtonsoft.Json(Json.NET)作为JSON序列化器,默认仅序列化/反序列化带get/set访问器的属性,不会处理普通的公共字段。你的Pets类中定义的是公共字段(如public bool Cat;),因此反序列化时这些字段会被初始化为bool类型的默认值false,而不会读取JSON中的对应值。

解决方案

方案1:将字段改为属性(推荐)

修改Pets类,把公共字段改为带get/set访问器的属性,符合.NET编码规范,同时让Json.NET能正常处理:

public class Pets
{
    public bool Cat { get; set; }
    public bool Dog { get; set; }
    public bool Bird { get; set; }
    public bool Mouse { get; set; }
}

方案2:配置Json.NET以支持字段序列化(如需保留字段)

如果必须保留公共字段,可以在项目的全局配置中修改Json.NET的序列化规则,让它包含公共字段:
在Global.asax.cs的Application_Start方法中添加以下配置:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // 配置Json.NET序列化器包含公共字段
    var jsonSettings = new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver
        {
            DefaultMembersSearchFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance
        }
    };
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jsonSettings;
}

验证

修改完成后重新运行项目,Controller就能正确读取Pets对象中的所有属性值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:40:09