如何修改代码以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
相关产品推荐
相关产品推荐

