简体   繁体   English

如何在 C# 中使用反射获取 Json 属性名称

[英]How to get Json Property name using reflection in C#

I have a class as mentioned below:我有一个如下所述的课程:

public class Employee {

    [JsonProperty("emp_id")]
    public int Id {get; set;}

    [JsonProperty("emp_fname")]
    public string Name {get;set;}

    [JsonProperty("emp_lname")]
    public string LastName {get;set;} 
}

In the above class, I have assigned Newtonsoft Attribute for serialization.在上面的课程中,我为序列化分配了 Newtonsoft 属性。

I have a object of class Employee and Now I would like to find the property by JsonProperty and get value of that property.我有一个Employee类的对象,现在我想通过JsonProperty查找该属性并获取该属性的值。

For example, I would like to get the value of the property for which JsonProprty attribute name is set to emp_lname例如,我想获取 JsonProprty 属性名称设置为emp_lname属性的值

Is there a way to find value like this using reflection?有没有办法使用反射找到这样的价值?

You can use Json.NET's own contract resolver for this purpose.为此,您可以使用 Json.NET 自己的合同解析器 Doing so will correctly handle properties with, and without, [JsonProperty(string name)] attributes added, as well as objects with naming strategies or data contract attributes applied directly.这样做将正确处理添加和不添加[JsonProperty(string name)]属性的属性,以及直接应用命名策略数据协定属性的对象。

First add the following method:首先添加以下方法:

public static partial class JsonExtensions
{
    static readonly IContractResolver defaultResolver = JsonSerializer.CreateDefault().ContractResolver;

    public static object GetJsonProperty<T>(T obj, string jsonName, bool exact = false, IContractResolver resolver = null)
    {
        if (obj == null)
            throw new ArgumentNullException(nameof(obj));
        resolver = resolver ?? defaultResolver;
        var contract = resolver.ResolveContract(obj.GetType()) as JsonObjectContract;
        if (contract == null)
            throw new ArgumentException(string.Format("{0} is not serialized as a JSON object", obj));
        var property = contract.Properties.GetProperty(jsonName, exact ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
        if (property == null)
            throw new ArgumentException(string.Format("Property {0} was not found.", jsonName));
        return property.ValueProvider.GetValue(obj); // Maybe check JsonProperty.Readable first, and throw an exception if not?
    }
}

And now you can do:现在你可以这样做:

var employee = new Employee
{
    LastName = "last name",
};

Console.WriteLine("Value of {0} is {1}.", "emp_lname", 
                  JsonExtensions.GetJsonProperty(employee, "emp_lname")); // Prints Value of emp_lname is last name.

If your app uses camel casing for JSON serialization by default, you can pass a CamelCasePropertyNamesContractResolver in for resolver like so:如果您的应用默认使用驼峰式大小写进行 JSON 序列化,您可以为resolver传递CamelCasePropertyNamesContractResolver ,如下所示:

Console.WriteLine("Value of {0} is {1}.", "emp_lname", 
                  JsonExtensions.GetJsonProperty(employee, "emp_lname", resolver : new CamelCasePropertyNamesContractResolver())); 

If you need to get a list of all JSON property names for a given type, see Get a list of JSON property names from a class to use in a query string :如果您需要获取给定类型的所有 JSON 属性名称列表,请参阅从类中获取 JSON 属性名称列表以在查询字符串中使用

public static partial class JsonExtensions
{
    public static string [] PropertyNames(Type type)
    {
        return PropertyNames(defaultResolver, type);
    }

    //Taken from this answer https://stackoverflow.com/a/45829514/3744182
    //To https://stackoverflow.com/questions/33616005/get-a-list-of-json-property-names-from-a-class-to-use-in-a-query-string
    public static string [] PropertyNames(this IContractResolver resolver, Type type)
    {
        if (resolver == null || type == null)
            throw new ArgumentNullException();
        var contract = resolver.ResolveContract(type) as JsonObjectContract;
        if (contract == null)
            return new string[0];
        return contract.Properties.Where(p => !p.Ignored).Select(p => p.PropertyName).ToArray();
    }
}

Demo fiddle here .演示小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM