如何在C#中使用反射获取Json属性名称 [英] How to get Json Property name using reflection in C#

查看:373
本文介绍了如何在C#中使用反射获取Json属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所述的课程:

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;} 
}

在上面的课程中,我分配了Newtonsoft Attribute进行序列化.

In the above class, I have assigned Newtonsoft Attribute for serialization.

我有一个 Employee 类的对象,现在我想通过 JsonProperty 查找该属性并获取该属性的值.

I have a object of class Employee and Now I would like to find the property by JsonProperty and get value of that property.

例如,我想获取JsonProprty属性名称设置为 emp_lname

For example, I would like to get the value of the property for which JsonProprty attribute name is set to emp_lname

是否有一种方法可以通过反射来找到价值?

Is there a way to find value like this using reflection?

推荐答案

您可以使用Json.NET自己的合同解析器为此目的.这样做将正确处理带有和不带有 [JsonProperty(string name)] 属性的属性,以及带有

You can use Json.NET's own contract resolver for this purpose. 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.

首先添加以下方法:

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.

默认情况下,如果您的应用使用骆驼套进行JSON序列化,则可以传递 CamelCasePropertyNamesContractResolver 输入 resolver ,如下所示:

If your app uses camel casing for JSON serialization by default, you can pass a CamelCasePropertyNamesContractResolver in for resolver like so:

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

如果需要获取给定类型的所有JSON属性名称的列表,请参见 获取JSON属性的列表要在查询字符串中使用的类中的名称 :

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:

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();
    }
}

演示小提琴此处.

这篇关于如何在C#中使用反射获取Json属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆