我有一个带有 JsonProperties 的类。
public class MyClass {
[JsonProperty("Editor 1")]
public string Editor {get; set;}
}
我想避免在我的代码中使用魔法字符串。但我需要这个 JSON 属性的名称。
我正在尝试做这样的事情:
var name = typeof(MyClass).GetProperty(nameof(MyClass.Editor)).GetCustomAttribute<JsonPropertyAttribute>().Name;
但这行不通..
目标是拥有
name = "Editor 1"
但我正在努力获得这个结果。任何帮助将不胜感激。
谢谢
最佳答案
您只需更改您尝试在 JsonPropertyAttribute
上访问的属性的名称。 名称
不存在。您需要 PropertyName
。
var name = typeof(MyClass)
.GetProperty(nameof(MyClass.Editor))
.GetCustomAttribute<JsonPropertyAttribute>()
.PropertyName;
还有一个额外的好处,这里有一个小辅助方法,如果属性不存在或没有应用 JsonPropertyAttribute
,它会返回 null
。根据需要进行调整。
public static string GetJsonPropertyName(Type type, string propertyName)
{
if (type is null)
throw new ArgumentNullException(nameof(type));
return type.GetProperty(propertyName)
?.GetCustomAttribute<JsonPropertyAttribute>()
?.PropertyName;
}
关于c# - 使用反射 C# 获取 JsonProperty 属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57894327/