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

如何修改代码以JsonProperty名称作为字典的键?

解决方案

原类定义

public class Client {
    [JsonProperty("first_name")]
    public string FirstName { get; set; }
    [JsonProperty("last_name")]
    public string LastName { get; set; }
}

修改后代码

要实现用JsonProperty指定的名称作为字典键,核心是通过反射提取属性上的特性值,修改后的代码如下:

// 需先引入命名空间:using Newtonsoft.Json;
var propertyValuesByName = client.GetType().GetProperties()
    .Where(pi => pi.PropertyType == typeof(string))         
    .Select(pi => 
    {
        // 获取属性上的JsonProperty特性实例
        var jsonAttribute = pi.GetCustomAttribute<JsonPropertyAttribute>();
        // 优先使用特性指定的名称,无特性则 fallback 到原属性名
        var dictKey = jsonAttribute?.PropertyName ?? pi.Name;
        return new { Value = (string)pi.GetValue(client), Key = dictKey };
    })
    .ToDictionary(item => item.Key, item => item.Value);

关键说明

  • GetCustomAttribute<JsonPropertyAttribute>():从属性元数据中读取JsonProperty特性,若属性未标记该特性则返回null
  • 空合并运算符??:处理无特性的边界场景,保证即使属性没有JsonProperty标记,也能正常用原属性名作为字典键
  • 最终通过ToDictionary将提取到的特性名称(或原属性名)设为键,属性值设为值,构建目标字典

内容的提问来源于stack exchange,提问作者Fazla Elahi Md Jubayer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:16:14