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

使用System.Text.Json反序列化遇构造参数绑定错误的技术问询

System.Text.Json反序列化错误排查与修复

错误信息

Each parameter in the deserialization constructor on type 'kitaphabitati.webmvc.helpers.viewalerts.models.messagedata' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'jsonserializeroptions.includefields' is enabled. The match can be case-insensitive

用户问题

  1. 该错误产生的原因是什么?我的MessageData类构造函数为何与JSON数据不匹配?
  2. 如何解决该错误?具体应如何修复JSON反序列化?

用户代码

public class MessageData
{
    public string Title { get; set; }
    public string Content { get; set; }

    public MessageData(Title title, string content)
    {
        Title = title.ToString().ToLower();
        Content = content;
    }
}

错误原因

  1. 构造函数参数与属性类型不匹配:MessageData的Title属性是string类型,但构造函数第一个参数是Title枚举(或自定义类型)。System.Text.Json反序列化时,会尝试将JSON中的Title字符串值直接绑定到构造函数的Title参数,类型不兼容导致绑定失败。
  2. 构造函数绑定规则不满足:System.Text.Json要求构造函数的每个参数必须匹配类的属性/字段(名称大小写不敏感),且参数类型要和对应属性类型兼容。这里构造函数的title参数类型和类的Title属性类型不一致,无法完成自动映射。

修复方案

方案一:修改构造函数参数类型为string

将构造函数第一个参数改为string,内部处理枚举转换逻辑:

public class MessageData
{
    public string Title { get; set; }
    public string Content { get; set; }

    public MessageData(string title, string content)
    {
        if (Enum.TryParse<Title>(title, ignoreCase: true, out var titleEnum))
        {
            Title = titleEnum.ToString().ToLower();
        }
        else
        {
            // 处理无效Title值,可自行调整逻辑
            Title = title.ToLower();
        }
        Content = content;
    }
}

方案二:添加无参构造函数

System.Text.Json优先使用无参构造函数,绕过构造参数不匹配问题,后续再处理枚举转换:

public class MessageData
{
    public string Title { get; set; }
    public string Content { get; set; }

    // 添加无参构造函数
    public MessageData() { }

    public MessageData(Title title, string content)
    {
        Title = title.ToString().ToLower();
        Content = content;
    }

    // 可选:提供枚举转换方法,在反序列化后调用
    public void SetTitleFromEnum(Title title)
    {
        Title = title.ToString().ToLower();
    }
}

方案三:使用JsonConstructor特性指定映射

保留现有构造函数,通过特性明确参数与属性的映射,同时确保JSON值能解析为Title枚举:

using System.Text.Json.Serialization;

public class MessageData
{
    public string Title { get; set; }
    public string Content { get; set; }

    [JsonConstructor]
    public MessageData(Title title, string content)
    {
        Title = title.ToString().ToLower();
        Content = content;
    }
}

注意:此方案要求JSON中的Title值是Title枚举的有效成员(名称或对应数值),否则会触发解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:37:14