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

DataTable调用ToList反序列化时字段名含空格或特殊字符如何正确取值

问题根因

你当前的映射逻辑仅读取Display特性作为自定义列名匹配依据,而实体类上给ProductPN属性加的[JsonProperty]是Newtonsoft.Json用于序列化/反序列化的特性,你的映射代码并未识别该特性,因此无法将属性和Product P/N列对应上,才会返回null。

方案1:直接复用现有逻辑(无需修改映射代码)

把实体类的特性换成Display即可,你的ToDescription方法本来就支持读取该特性的配置:

using System.ComponentModel.DataAnnotations; // 找不到Display特性时引入该命名空间

public class TableData
{
    [Display(Name = "Product P/N")]
    public string ProductPN{ get; set; }
    public string Brand { get; set; }
}

改完之后直接运行就能正常获取Product P/N列的值。

方案2:让映射逻辑支持JsonProperty特性

如果你不想修改现有实体类的特性,只需要调整ToDescription扩展方法,增加对JsonProperty特性的识别即可:

using Newtonsoft.Json; // 注意引入Newtonsoft.Json对应的命名空间

public static string ToDescription(this PropertyInfo Object)
{
    // 优先读取JsonProperty特性的列名配置
    var jsonAttrs = Object.GetCustomAttributes(typeof(JsonPropertyAttribute), false);
    if (jsonAttrs != null && jsonAttrs.Length > 0) 
        return ((JsonPropertyAttribute)jsonAttrs[0]).PropertyName;
    
    // 保留原有Display特性的识别逻辑
    var displayAttrs = Object.GetCustomAttributes(typeof(Display), false);
    if (displayAttrs != null && displayAttrs.Length > 0) 
        return ((Display)displayAttrs[0]).Text;
    
    return Object.Name;
}

修改后原有实体类无需调整,即可正常匹配到带空格、特殊符号的列名。

注意事项

  • 特性中配置的列名要和DataTable中的列名完全一致,包括大小写、特殊符号,避免匹配失败。
  • 方案2需要确保项目已经引用了Newtonsoft.Json包,否则会找不到JsonPropertyAttribute类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:06:02