【发布时间】:2023-01-06 23:28:14
【问题描述】:
我有一个类如下:
public class Client {
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
}
使用以下代码,我可以在该类对象的字典中获取属性和值:
var propertyValuesByName = client.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => new { Val = (string) pi.GetValue(client), Name = pi.Name })
.ToDictionary(pi => pi.Name, pi => pi.Val);
因此字典包含属性名称作为键,属性值作为值。但我想要的是,获取字典,其中键将是对象 JsonProperty 名称而不是真正的属性名称,这意味着我想要“first_name”作为键而不是“FirstName”。我怎样才能修改上面的代码来实现这一点?
【问题讨论】:
-
您可以在此处添加示例 JSON 吗?
标签: c# json asp.net-core json.net