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

.NET Core 6.0 POST API接收无固定结构JSON(System.Object)异常问题

解决.NET 6中POST API接收动态JSON作为Object类型的问题

问题原因

.NET Core 3.0及后续版本(包括6.0)默认采用System.Text.Json作为JSON序列化器,而.NET Core 2.2默认使用Newtonsoft.Json。两者对object类型属性的动态JSON处理逻辑存在差异:

  • Newtonsoft.Json会自动将JSON对象转换为JObject实例并赋值给object属性
  • System.Text.Json无法自动将JSON对象映射到object类型,会抛出序列化异常,这就是你遇到的问题。

解决方案

方案1:切换回Newtonsoft.Json(保持原有代码兼容)

这是最直接的兼容方案,无需修改现有模型和业务代码,只需配置项目使用Newtonsoft.Json替代默认序列化器:

  1. 安装NuGet包:Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. 在Program.cs中配置服务:
var builder = WebApplication.CreateBuilder(args);

// 添加控制器并启用NewtonsoftJson
builder.Services.AddControllers().AddNewtonsoftJson();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

配置完成后,原有代码的object属性会恢复.NET Core 2.2时的行为,自动解析动态JSON。

方案2:使用JsonElement/JsonObject替代Object类型(基于System.Text.Json)

如果不想依赖Newtonsoft.Json,可以改用.NET 6+支持的JsonElement或JsonObject类型,它们能原生兼容System.Text.Json的动态JSON解析:

  1. 修改模型类:
public class NunjucksDataModal
{
    public int web_id { get; set; }
    public int component_type_id { get; set; }
    // 替换object为JsonElement(.NET 6+支持)
    public JsonElement json { get; set; }
    // 或者使用JsonObject(.NET 7+支持,操作更便捷)
    // public JsonObject json { get; set; }
}
  1. 访问动态JSON属性的示例:
// 从JsonElement中获取product_id
var productId = modal.json.GetProperty("product_id").GetString();

方案3:使用dynamic类型(有限场景适用)

可以将object替换为dynamic类型,System.Text.Json会将JSON对象解析为JsonElement并包装为dynamic:

public class NunjucksDataModal
{
    public int web_id { get; set; }
    public int component_type_id { get; set; }
    public dynamic json { get; set; }
}

注意:访问dynamic属性时需要显式转换类型,例如:

string productId = modal.json.product_id.ToString();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:15:14