c# - 使用反射 C# 获取 JsonProperty 属性的名称

标签 c# .net

我有一个带有 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/

相关文章:

c# - .NET 的 SSO 选项

c# - Include 内使用的 Lambda 表达式无效

c# - 系统.InvalidOperationException : 'There is an error in XML document (0, 0).'

c# - AutoFixture 无法创建匿名 MVC Controller

c# - TaskFactory 内部任务永远不会被执行并且始终处于 WaitingForActivation 状态

c# - 使用StreamReader复制图像时损坏

c# - 我如何知道 ComboBox 中的值何时为 "re-selected"?

c# - 解析 JToken 得到 Key Value 对

c# - Unity3D : Cannot change scripting backend to . 网络

c# - 如何在 C# 中获取特定的文化数字模式